关注小程序 找一找教程网-随时随地学编程

SqlServer教程

SQL SERVER 的窗体函数OVER的使用:row_number/rank/dense_rank

举个例子给大家加深印象,也方便理解:

1.目前有这几笔数据:

  Select '1班' banji,'张三' as name ,56 as score
into #studentSoure
union all 
Select '1班' banji,'李四' as name ,66 as score
union all 
Select '2班' banji,'王五' as name ,76 as score
union all 
Select '2班' banji,'王三' as name ,84 as score
union all 
Select '2班' banji,'王四' as name ,76 as score
select * from #studentSoure   View Code

2.简单明了看到所有同学和自己班级成绩最好的做比较

 select banji,name,score,max(score) over(partition by banji) avg_score
from #studentSoure  

相同的道理,上面的max也可以改成min,avg等

 

3.row_number()、rank()、dense_rank()方法的使用

--row_number() 则在排序相同时不重复,会根据顺序排序。

--rank()排序相同时会重复,总数不会变 ,意思是会出现1、1、3这样的排序结果;

--dense_rank() 排序相同时会重复,总数会减少,意思是会出现1、1、2这样的排序结果。

 

 

 select banji,name,score,ROW_NUMBER() over(partition by banji order by score) avg_score
from #studentSoure 
select banji,name,score,rank() over(partition by banji order by score) avg_score
from #studentSoure 
select banji,name,score,dense_rank() over(partition by banji order by score ) avg_score
from #studentSoure