开发者

SQL Select top frequent records

开发者 https://www.devze.com 2022-12-14 13:30 出处:网络
I have the following table: Table +----+------+-------+ ID | Name | Group | +----+------+-------+ 0|a|1|

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).

开发者_如何学JAVA

Thank you.


SELECT TOP(20) [Name], Count(*) FROM Table
WHERE [Group] = 1
GROUP BY [Name]
ORDER BY Count(*) DESC


SELECT Top(20) 
   name, group, count(*) as occurences
FROM yourtable
GROUP BY name, group
ORDER BY count(*) desc


SELECT
    TOP 20
    Name,
    Group,
    COUNT(1) Count,
FROM
    MyTable
GROUP BY
    Name,
    Group
ORDER BY
    Count DESC
0

精彩评论

暂无评论...
验证码 换一张
取 消