一、需求
之前sql server 的排名函數(shù)用得最多的應該是RoW_NUMBER()了,我通常用ROW_NUMBER() + CTE 來實現(xiàn)分頁;今天逛園,看到另一個內(nèi)置排名函數(shù)還不錯,自己順便想了一個需求,大家可以花1分鐘先想想要怎么實現(xiàn)。
需求很簡單:求成績排名前五的學生信息。
例如:
由于成績可以并列,所以前五名可能有多個。例如:
測試數(shù)據(jù):
declare @t table (ID int, StudentName nvarchar(15), Score int) insert into @t select 1,'黃一',99 union all select 2,'吳二',99 union all select 3,'張三',99 union all select 4,'李四',98 union all select 5,'王五',97 union all select 6,'趙六',96 union all select 7,'田七',95 union all select 8,'紀八',94 union all select 9,'邱九',93 union all select 10,'林十',92
二、自己實現(xiàn)
我的想法:既然可能出現(xiàn)并列,那么就用 DISTINCT 找到前五的成績。ok,代碼如下:
select t1.* from @t t1 join(select distinct top 5 Score from @t order by Score desc) t2 on t1.Score = t2.Score
看起來和上面的要求的結(jié)果還是不太一樣,少了排序,當然我們可以在程序處理,這不是問題。
三、使用內(nèi)置排名函數(shù) DENSE_RANK
其實sql server已經(jīng)內(nèi)置了這樣的函數(shù)可以幫助我們輕松實現(xiàn),ok,直接上代碼:
;with cte as( select dense_rank() over(order by Score desc) rank,* from @t ) select * from cte where rank 6
四、擴展,內(nèi)置排名函數(shù)RANK
與 DENSE_RANK類似還有一個RANK函數(shù),不過RANK函數(shù)不會順序排名,而是根據(jù)序號排。有點繞,把上面的函數(shù)改為RANK()就知道了,得到的結(jié)果如下:
以上就是sql server排名函數(shù)DENSE_RANK的使用方法,分享了自己的一些想法,希望對大家的學習有所啟發(fā)。