views:

214

answers:

3

Hi,

I have the following table:

Table
+----+------+-------+
| ID | Name | Group |
+----+------+-------+
| 0  |   a  |   1   | 
| 1  |   a  |   1   | 
| 2  |   a  |   2   |
| 3  |   a  |   1   |
| 4  |   b  |   1   |
| 5  |   b  |   2   |
| 6  |   b  |   1   |
| 7  |   c  |   2   |
| 8  |   c  |   2   |
| 9  |   c  |   1   |
+----+------+-------+

I would like to select top 20 distinct names from a specific group ordered by most frequent name in that group. The result for this example for group 1 would return a b c ( a - 3 occurrences, b - 2 occurrences and c - 1 occurrence).

Thank you.

+8  A: 
SELECT TOP(20) [Name], Count(*) FROM Table
WHERE [Group] = 1
GROUP BY [Name]
ORDER BY Count(*) DESC
Mark Byers
are the result names gonna be distinct?
negative
Yes, hence the *GROUP BY*
astander
+2  A: 
SELECT
    TOP 20
    Name,
    Group,
    COUNT(1) Count,
FROM
    MyTable
GROUP BY
    Name,
    Group
ORDER BY
    Count DESC
David Hedlund
This would make a good view or inner select. You need a WHERE clause to get what he's asking for though.
Mark Byers
+3  A: 
SELECT Top(20) 
   name, group, count(*) as occurences
FROM yourtable
GROUP BY name, group
ORDER BY count(*) desc
maxwell
You probably want a DESC on your ORDER BY. He wants the most frequent, not the least frequent.
Mark Byers
@Mark Byers Thanks!
maxwell