sql server 分组,取每组的前几行数据

时间:2022-09-23 08:39:17

sql中group by后,获取每组中的前N行数据,目前我知道的有2种方法

比如有个成绩表: 里面有字段学生ID,科目,成绩。我现在想取每个科目的头三名。

  1.   子查询

select * from score s where StudentName in (
select top 3 StudentName from score where s.Subjects = Subjects 
group by Subjects,StudentName,Score order by Score desc)
group by Subjects,StudentName,Score order by Subjects,Score desc

2.    用rowNumber函数

select Subjects,StudentName,Score from 
(select *,
ROW_NUMBER() over(partition by subjects order by score desc) rowNum
from Score) as s where s.rowNum <= 3
group by Subjects,StudentName,Score order by Subjects,Score desc


以上的2种结果都是一样的。如果还有其他的方法,以后补充



表和表的数据

Create table Score(StudentName char(10),Subjects char(20), Score float)


insert into Score  values('小明','语文',90),
('小明','数学',80),
('小明','英语',60),
('小红','语文',93),
('小红','数学',92),
('小红','英语',91),
('小花','语文',50),
('小花','数学',30),
('小花','英语',70),
('小草','语文',95),
('小草','数学',86),
('小草','英语',62),
('小刚','语文',78),
('小刚','数学',68),
('小刚','英语',76),
('小柔','语文',56),
('小柔','数学',86),
('小柔','英语',88),
('小陈','语文',77),
('小陈','数学',88),
('小陈','英语',99)