178.分数排名
链接:https://leetcode-cn.com/problems/rank-scores
编写一个 SQL 查询来实现分数排名。如果两个分数相同,则两个分数排名(Rank)相同。请注意,平分后的下一个名次应该是下一个连续的整数值。换句话说,名次之间不应该有“间隔”。
+----+-------+
| Id | Score |
+----+-------+
| 1 | 3.50 |
| 2 | 3.65 |
| 3 | 4.00 |
| 4 | 3.85 |
| 5 | 4.00 |
| 6 | 3.65 |
+----+-------+
例如,根据上述给定的 Scores 表,你的查询应该返回(按分数从高到低排列):
+-------+------+
| Score | Rank |
+-------+------+
| 4.00 | 1 |
| 4.00 | 1 |
| 3.85 | 2 |
| 3.65 | 3 |
| 3.65 | 3 |
| 3.50 | 4 |
+-------+------+
题解一:
select a.Score,
count(distinct b.Score) as Rank --- 对Score去重计数,当做排名
from Scores a, Scores b
where b.Score>=a.Score --- b表中有x个非重复值大于等于a表当前值,则a表当前值排名为x
group by a.id --- 为了让Score全部显示出来,避免只显示去重的Score
order by a.Score DESC
;
关键点:
- group by a.id 如果去掉的话,会缺数据
题解二:
select
a.Score as Score ,
(select count(distinct b.Score) from Scores b where b.Score >=a.Score) as rank
from Scores a
order by Score DESC;
关键点:
使用子查询结果作为列结果,两层嵌套循环,简单粗暴。