获取具有最大计数的所有组

时间:2013-01-29 03:47:03

标签: sql sql-server

假设我现在有一个表T,就像这样:

A|B
1|1 
1|2 
2|1 
2|2 
2|3 
3|1 
3|2 
3|3 

使用select A, count(*) from T group by A我们应该得到:

A|count(*)
1|2
2|3
3|3

现在我需要获取上一个查询中的最后两行 - 其最大值为count(*)。如何在单个查询中执行此操作?

感谢。

2 个答案:

答案 0 :(得分:3)

WITH recordList
AS
(
    SELECT  A, COUNT(*) totalCount,
            DENSE_RANK() OVER (ORDER BY COUNT(*) DESC) rn
    FROM    tableName
    GROUP BY A
)
SELECT  A, totalCount
FROM recordLIst
WHERE rn = 1

答案 1 :(得分:1)

;WITH a(A,C,R) AS
(
  SELECT A, COUNT(*), RANK() OVER (ORDER BY COUNT(*) DESC)
  FROM dbo.T GROUP BY A
)
SELECT A, C FROM a WHERE R = 1;