问题:编写一个 SQL 查询来实现评分排名。如果两个分数相同,则两个分数排名(Rank)相同。
评分表ratings方法一:不运用dense_rank(),运用子查询
解决这一问题可以分为两个步骤:
步骤一:降序排列分数
select a.Rating as Rating from ratings a order by a.Rating DESC;
步骤二:每个评分对应的排名
思路:可以先提取出大于等于X的所有分数集合H,将H去重后的元素个数就是X的排名。
先提取集合H:
select b.Rating from ratings b where b.Rating>= X;
再求出集合H去重之后的元素个数:
select count(distinct b.Score) from Scores b where b.Score >= X as Rank;
最终将两个步骤结合:
select a.Rating as Rating,
(select count(distinct b.Rating) from ratings b where b.Rating >= a.Rating) AS "Rank"
from ratings a order by a.Rating DESC;
方法二:运用dense_rank()
select Rating, dense_rank() over (order by Rating desc) as "Rank" from ratings;
附:mysql中Rank()和dense_rank()的区别
不同点:RANK()是跳跃排序,即如果有两条记录重复,接下来是第三级别
如:1 2 2 4,会跳过3
DENSE_RANK()是连续排序,即如果有两条记录重复,接下来是第二级别
如:1 2 2 3
网友评论