简体   繁体   中英

How do i perform grouped ranking in MySQL with row ties?

ID_STUDENT | ID_CLASS | GRADE | RANK

2      |    1     |  90   |  1
1      |    1     |  90   |  1
3      |    1     |  90   |  1
4      |    1     |  70   |  4
6      |    2     |  90   |  1
1      |    2     |  80   |  2
5      |    2     |  78   |  3
7      |    3     |  90   |  1
6      |    3     |  50   |  2

How should i sort and rank the data to get the above result? Thanks in advance

One method is with a subquery:

select sc.*,
       (select count(*) + 1
        from studentclass sc2
        where sc2.grade > sc.grade and sc2.id_class = sc.id_class
       ) as rank
from studentclass sc order by id_class, grade;

In ANSI SQL (and most other databases), this is provided by the rank() function. You might be interested in the differences between rank() , dense_rank() , and row_number() .

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