怎么求得每个班分数最后的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
/*
班级分数
A84
A70
B32
C52
D30
E68
*/