下面我們分2種情況,來寫出數據排名的實現過程。測試數據如下:
排名後的結果如下:
Access
復制代碼 代碼如下:
select name, score, (select iif(isnull(sum(1)), 1, sum(1) + 1) from score_rank where score > a.score) as rank from score_rank a order by score desc
sqlserver
復制代碼 代碼如下:
select name, score, (select ISNULL(sum(1),0) + 1 from score_rank where score > a.score) as rank from score_rank a order by score desc
對於 SQL SERVER 2005 及更高版本
復制代碼 代碼如下:
SELECT name, score, RANK() OVER (ORDER BY score DESC) AS [rank], DENSE_RANK() OVER (ORDER BY score DESC) AS [rank1], NTILE(4) OVER(ORDER BY score DESC) AS [rank2] FROM score_rank ORDER BY score DESC;