我们说我有以下内容:
DECLARE @Name TABLE (Name VARCHAR(MAX));
INSERT INTO @Name VALUES ('bob'),('bob'),('john'),('john'),('mark'),('mark'),('mark'),('lisa');
SELECT Name,
COUNT(Name) AS TOTALS
FROM @Name
GROUP BY Name
ORDER BY TOTALS DESC;
我如何使用Rank()或Dense_Rank()来获得基于计数的排名?
答案 0 :(得分:3)
如果您想要排名列,可以将其与group by
:
SELECT n.Name, COUNT(*) as TOTALS,
RANK() OVER (ORDER BY COUNT(*) DESC) as Total_Rank
FROM @Name n
GROUP BY n.Name
ORDER BY TOTALS DESC;
答案 1 :(得分:1)
试试这个:
SELECT *
, RANK() OVER(ORDER BY totals DESC) AS Rank
FROM
(
SELECT Name,
COUNT(Name) AS TOTALS
FROM @Name
GROUP BY Name
) a