【sql 练习题 36,37】查询每门功成绩最好的前两名,统计每门课程的学生选修人数(超过 5 人的课程才统计)

题目36:查询每门功成绩最好的前两名

分析:先用自己交自己,条件为a.courseid = b.courseid and a.score<b.score,其实就是列出同一门课内所有分数比较的情况。

           通过a.studentid和a.courseid可以联合确定这个同学的这门课的这个分数究竟比多少个其他记录高/低,

          如果这个特定的a.studentid和a.courseid组合出现在这张表里的次数少于2个,那就意味着这个组合(学号+课号+分数)是这门课里排名前二的。

          所以下面这个计算中having count 部分其实count()或者任意其他列都可以,这里制定了一个列只是因为比count()运行速度上更快。

select a.studentid,a.courseid,a.score from student_score as a
left join student_score as b
on a.courseid = b.courseid and a.score<b.score
group by a.courseid, a.studentid
having count(b.courseid)<2
order by a.courseid;

题目37:.统计每门课程的学生选修人数(超过 5 人的课程才统计)

分析:这题目的思路已经写过很多次了  group by courseid count(student)

SELECT courseid, COUNT(studentid) FROM student_score GROUP BY courseid HAVING COUNT(studentid)>5

原文地址:https://www.cnblogs.com/yuanyuan2017/p/11378194.html