一起使用分组方式和排序方式

时间:2018-08-19 14:42:02

标签: sql oracle

我难以在按功能分组中包含按功能排序。

我想找出3年中每年出勤率最高的学生。

表格:

学生

studentPIN | fName | lName | StudyYear 

    1          x       x         1
    2          x       x         2
    3          x       x         3
    4          x       x         2

出勤记录 N.B身份是指他们是否上过课。

ClassID | StudentPin | Status 
   12          1         NO
   23          2         YES
   34          3         YES

目前,我已经能够计算出每个学生上课的次数。

这是我目前正在使用的东西:

Select student.fname, student.lname, STUDENT.STUDYYEAR,
SUM(CASE ATTENDANCELOG.STATUS WHEN 'YES' THEN 1 ELSE NULL END) AS Attended 
from student 
Join ATTENDANCELOG on student.studentpin=ATTENDANCELOG.studentpin
GROUP BY STUDENT.STUDYYEAR, STUDENT.FNAME, STUDENT.LNAME

我只是停留在如何从高出席率到最低出席率的顺序上,然后在三年中的每一年都选择排名最高的那个。

谢谢。

2 个答案:

答案 0 :(得分:0)

使用row_number()

select fname, lname, studyyear, attended
from (select s.fname, s.lname, s.STUDYYEAR,
             SUM(CASE al.STATUS WHEN 'YES' THEN 1 ELSE 0 END) AS Attended,
             row_number() over (partition by s.studyyear
                                order by SUM(CASE al.STATUS WHEN 'YES' THEN 1 ELSE 0 END) desc
                               ) as seqnum
      from student s Join
           ATTENDANCELOG al
           on s.studentpin = al.studentpin
      group by s.STUDYYEAR, s.FNAME, s.LNAME
     ) s
where seqnum = 1;

答案 1 :(得分:0)

Select student.fname, student.lname, STUDENT.STUDYYEAR,
SUM(CASE ATTENDANCELOG.STATUS WHEN 'YES' THEN 1 ELSE NULL END) AS Attended 
from student 
Join ATTENDANCELOG on student.studentpin=ATTENDANCELOG.studentpin
GROUP BY STUDENT.STUDYYEAR, STUDENT.FNAME, STUDENT.LNAME
ORDER BY 4 desc;