SQL 查询表中每门课程成绩最好的前n名学生 优于group by语句的方法

假设有表score记录学生id(student_id)、课程id(course_id)和课程分数(score)
在这里插入图片描述
要求查询表中每门课程成绩最好的前2名学生的id、相应课程id和分数。则可以用如下sql语句

select * from score score1 where(
	select count(1) 
	from score score2 
	where score1.course_id = score2.course_id and score2.score >= score1.score
)<=2
order by score1.course_id asc, score1.score desc;

如果要查询前n位,则将上述语句中的<=2替换为<=你想要的的数字即可

发布了219 篇原创文章 · 获赞 983 · 访问量 136万+

猜你喜欢

转载自blog.csdn.net/baishuiniyaonulia/article/details/105107267