SQL Select Top Records

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 the top 20 names from a particular group, sorted by the most common name in that group. The result for this example for group 1 will return a b c(a - 3 occurrences, b - 2 occurrences and c - 1 occurrence).

Thanks.

+5
source share
3 answers
SELECT TOP(20) [Name], Count(*) FROM Table
WHERE [Group] = 1
GROUP BY [Name]
ORDER BY Count(*) DESC
+13
source
SELECT Top(20) 
   name, group, count(*) as occurences
FROM yourtable
GROUP BY name, group
ORDER BY count(*) desc
+4
source
SELECT
    TOP 20
    Name,
    Group,
    COUNT(1) Count,
FROM
    MyTable
GROUP BY
    Name,
    Group
ORDER BY
    Count DESC
+2
source

All Articles