简体   繁体   中英

Get top records for each group in sql

I have a table which has 3 columns StudentID, Score and ClassNumber. What I need now is to select top 5 students of each Class (according to their Score result).

For example if there are 20 students in Class1, 40 students in Class2 and students in Class3, I need to select 15 top score students for each Class(5 for Class1, 5 for Class2, 5 for Class3)

How can I do this in one SQL query?

Do you mean somthing like this?

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

Solution in 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;

Solution in 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM