2 回答

TA貢獻1880條經驗 獲得超4個贊
你好,這個查詢比較復雜,希望你能仔細研習,希望可以幫助到你。
由于測試數據的數據量不大,我提供給你的這個例子中取得是排行前3的學生,你如果想測試排名前五的,加數據并且改一下SQL中的"rank<=5"即可。
SQL查詢語句如下:
select s.name as student,c.name as course,score from (select sid,cid
,score,rank from (select ff.sid,ff.cid,ff.score,if(@pcid=ff.cid,@rank:=@rank+1,@rank:=1) as rank,@pcid:=ff.cid from (select sid,cid,score from score order by cid asc,score desc) ff) result having rank<=3) aa inner join Student s on aa.sid=s.id inner join Course c on aa.cid=c.id;
測試數據如圖所示:
執行的結果如下:
+---------+--------+-------+
| student | course | score |
+---------+--------+-------+
| s1 | one | 80 |
| s3 | one | 56 |
| s5 | one | 45 |
| s1 | two | 94 |
| s2 | two | 84 |
| s3 | two | 77 |
+---------+--------+-------+
6 rows in set

TA貢獻1804條經驗 獲得超8個贊
select sname,cname,score from (
select sname,cname,score, row_number() over(partition by cid order by score desc) "row" from
(select student.name sname,course.name cname,score.score from score join student on score.sid = student.id join course on score.cid = course.id)
) where "row" <=5
添加回答
舉報