数据库专题-leetcode178. 分数排名

题目及分析

题目

编写一个 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 |
+-------+------+

分析

依照提议,需要知道分数的排名降序,所以order by desc .
第二列排名分析(参考题解):排名和人数无关,排名是一个去重后的位置。
比如要知道4.00分数在什么排名,可以取>=4.00的去重数量,这样4.00的排名就是结果集合里面的总数了。
所以依照这个思路:要知道4.00的排名:select count(distinct s2.Score) from Scores s2 where s2.Score>=s.Score

所以可以分为2步得到结果:
第一步后者降序后的结果:

select s.Score
from Scores s
order by s.Score desc

第二步取得当前分数在全部分数里面的排名

select count(distinct s2.Score) 
from Scores s2 
where s2.Score >= s.Score

合并在一起即可。

示例参考

select s.Score,
(
    select count(distinct s2.Score) 
    from Scores s2 
    where s2.Score >= s.Score
) Rank
from Scores s
order by s.Score desc

看题解还有其他解法,比如定义变量@判断,还有窗口函数,后续研究一下也会加上学一下。

猜你喜欢

转载自www.cnblogs.com/fabaogege/p/12209289.html