SQL选择最常见的记录

时间:2009-12-18 07:25:59

标签: sql sql-server

我有下表:

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   |
+----+------+-------+

我想从该组中最常用名称排序的特定组中选择前20个不同的名称。第1组的此示例的结果将返回a b c( a - 3次发生,b - 2次发生,c - 1次发生)。

谢谢。

3 个答案:

答案 0 :(得分:13)

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

答案 1 :(得分:5)

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

答案 2 :(得分:2)

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