題目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

