当前位置: 代码迷 >> Sql Server >> 如何求得每个班分数最后的2名
  详细解决方案

如何求得每个班分数最后的2名

热度:64   发布时间:2016-04-24 20:31:08.0
怎么求得每个班分数最后的2名?
班级    分数
A       30
A       50
C       52
D       30
A       84
E       68
A       70
B       32

如题怎么按班级分组后求出,分数最底的两名

------解决方案--------------------
if OBJECT_ID('tempdb..#temp', 'u') is not null   drop table #temp;
go
create table #temp( [班级] varchar(100), [分数] INT);
insert #temp
select 'A','30' union all
select 'A','50' union all
select 'C','52' union all
select 'D','30' union all
select 'A','84' union all
select 'E','68' union all
select 'A','70' union all
select 'B','32' 

--SQL:
;WITH CTE AS
(
SELECT ROWID=ROW_NUMBER() OVER(PARTITION BY [班级] ORDER BY 分数 DESC),*
from #temp
)
SELECT [班级],分数 FROM CTE
WHERE ROWID <= 2
/*
班级 分数
A 84
A 70
B 32
C 52
D 30
E 68
*/
  相关解决方案