sqlserver 班级排名_Sqlserver:班级排名问题(转发)
id,name(人名),class(班級),fen(分數)
1? jj? ? ? ? ? 1? ? ? ? ? 88
2? j1? ? ? ? ? 1? ? ? ? ? ? 90
3? j2? ? ? ? ? ? 2? ? ? ? 70
選出每個班級頭兩名分數, 顯示班級,人名,分數????????
create table #t (id int,name varchar(20),class varchar(10),fen int)
insert into #t
select 1,'jj','1',88 union all
select 2,'j1','1',90 union all
select 3,'j2','1',70 union all
select 4,'j3','2',89 union all
select 5,'ja','3',96 union all
select 6,'jb','3',63
解法一:
select *
from #t t
where (select count(*) from #t where class="t".class and fen > t.fen) =0 -- 第一名
where (select count(*) from #t where class="t".class and fen > t.fen) =1 -- 第二名
where (select count(*) from #t where class="t".class and fen > t.fen) <2 -- 前2名
where (select count(*) from #t where class="t".class and fen < t.fen) =0 -- 倒數第一名
where (select count(*) from #t where class="t".class and fen < t.fen) =1 -- 倒數第二名
where (select count(*) from #t where class="t".class and fen < t.fen) <2 -- 倒數前2名
解法二:
select t.* from #t t where fen in (select top 2 fen from #t where class = t.class) order by class,fen
解法三:
select *
from
(
select row_number() over(partition by? class order by fen desc) as rank,* from #t
) t
where rank <=2
order by class,rank,fen
附注:排名函數
rank():稀疏排名,排名可能會并列,因此引起排名的數字間斷。如有兩個并列第一,則接下來的排名為第三!
dense_rank():非稀疏排名,排名可能會并列,但排名的數字不會間斷。如有兩個并列第一,則接下來的排名為第二!
ntile(group count):(抽屜分配)將數據按分組數分組 分配。主要是看總行數 是否 能被 組數 平均分配,如果不能平均分配,則會將數據有限分配到前面的組中!
row_number():分配唯一的邏輯行記錄的id,通常用于分頁用
over子句還支持聚合函數 和 窗口分區子句
解法四:
select distinct t.*
from #t a
cross apply (select top 2 * from #t b where a.class = b.class order by fen desc) as t --內部(左值)多值交叉表
order by t.class,t.fen desc
解法五:
select distinct t.*
from #t a
outer apply (select top 2 * from #t b where a.class = b.class order by fen desc) as t --外部(右值)多值交叉表
order by t.class,t.fen desc
總結
以上是生活随笔為你收集整理的sqlserver 班级排名_Sqlserver:班级排名问题(转发)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 命令行请求jsp页面_JSP 之 8种H
- 下一篇: 合泰单片机 熔丝_合泰单片机HT66F0