获取sql中每个组的最高记录

时间:2018-03-21 10:21:32

标签: sql greatest-n-per-group

我有一个表有3列StudentID,Score和ClassNumber。 我现在需要的是选择每个班级的前5名学生(根据他们的分数结果)。

例如,如果Class1中有20名学生,Class2中有40名学生,Class3中有40名学生,我需要为每个班级选择15名最高分学生(Class1为5,Class2为5,Class3为5)

如何在一个SQL查询中执行此操作?

2 个答案:

答案 0 :(得分:1)

你的意思是这样的吗?

with tmp as
(
    select ClassNumber,
           StudentID,
           Score,
           row_number() over (partition by ClassNumber order by Score desc) row_num, 
    from Student s
)

select ClassNumber, StudentID, Score
from tmp
where row_num <= 5
order by ClassNumber

答案 1 :(得分:1)

MYSQL中的解决方案:

SELECT StudentID, Score, ClassNumber
   FROM
     (SELECT StudentID, Score, ClassNumber, 
                  @class_rank := IF(@current_class = classNumber, @class_rank + 1, 1) AS class_rank,
                  @current_class := ClassNumber
       FROM student
       ORDER BY ClassNumber, score DESC
     ) ranked
   WHERE class_rank <= 5;

SQL SERVER中的解决方案:

select ClassNumber, StudentID, Score
from (
select ClassNumber,
           StudentID,
           Score,
           dense_rank() over (partition by ClassNumber order by Score desc) ranking 
    from Student s
) as t
where ranking <= 5
order by ClassNumber