假设我现在有一个表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(*)
。如何在单个查询中执行此操作?
感谢。
答案 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;