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;

结果

Sql -- 练习1 查询每科成绩前两名的学生信息_第1张图片

你可能感兴趣的:(数据库,基础知识)