且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MYSQL实现排名函数RANK,DENSE_RANK和ROW_NUMBER

更新时间:2022-06-30 05:52:11

  1. 并列跳跃排名
select
       score,
       (
           select count(score) + 1 from score s2 
           where s2.score > s.score
       ) ranking
from score s order by score desc;
  1. 并列连续排名
select
       score,
       (
           select count(distinct score) from score s2
           where s2.score >= s.score
       ) ranking
from score s order by score desc;
  1. 分组并列跳跃
select
       score,
       course_id,
       (
           select count(score) + 1 from score s2
           where s2.course_id = s.course_id and s2.score > s.score
        ) ranking
from score s
order by course_id,score desc;
  1. 分组并列连续
select
       score,
       course_id,
       (
           select count(distinct score) from score s2
           where s2.course_id = s.course_id and s2.score >= s.score
        ) ranking
from score s
order by course_id,score desc;