1. 程式人生 > >Sql -- 練習1 查詢每科成績前兩名的學生資訊

Sql -- 練習1 查詢每科成績前兩名的學生資訊

相關表資訊

問題

查詢每科成績前兩名的學生資訊

解決1

 SELECT hs2.student_name sna, hc2.course_name cna, m1.core
      FROM hand_student hs2,
           hand_course hc2,
           (SELECT hsc.student_no sno,
                   hsc.course_no cno,
                   hsc.core,
                   row_number() over(PARTITION BY hsc.course
_no ORDER BY hsc.core DESC) rn FROM hand_student_core hsc) m1 WHERE m1.rn <= 2 AND hs2.student_no = m1.sno AND hc2.course_no = m1.cno ORDER BY core;

解決2

with temps as(
    select hs.student_name,
           hsc.student_no,
           hc.course_name,
           hsc.course_no,
           hsc.core
      from
hand_student_core hsc, hand_student hs, hand_course hc where hc.course_no = hsc.course_no and hs.student_no = hsc.student_no) select * from (select t.*, row_number() over(partition by t.course_no order by t.core desc) asd from temps t) where
asd <= 2;

結果

這裡寫圖片描述