Buckle 178. Score ranking

Buckle 178. Score ranking

https://leetcode-cn.com/problems/rank-scores/

Write a SQL query to achieve score ranking.

If the two scores are the same, the two ranks are the same. Please note that the next place after the split should be the next consecutive integer value. In other words, there should be no "spacing" between rankings.

+----+-------+
| Id | Score |
+----+-------+
| 1  | 3.50  |
| 2  | 3.65  |
| 3  | 4.00  |
| 4  | 3.85  |
| 5  | 4.00  |
| 6  | 3.65  |
+----+-------+

For example, based on the Scores table given above, your query should return (in order of highest to lowest score):

+-------+------+
| Score | Rank |
+-------+------+
| 4.00  | 1    |
| 4.00  | 1    |
| 3.85  | 2    |
| 3.65  | 3    |
| 3.65  | 3    |
| 3.50  | 4    |
+-------+------+

 

第一步将score排序,以a表保存
select a.score 
from scores a
order by a.score desc

第二步,rank排名问题,首先是用distinct去重,接着是where筛选出大于等于a.score的行,最后是计数(重复次数和大于等于a.score的行)
select count(distinct b.score)
from scores b
where b.score>=a.score

合并起来,
select a.score,
(select count(distinct b.score)
from scores b
where b.score>=a.score) as Rank
from scores a
order by a.score desc

 

Buckle the answer:

最后的结果包含两个部分,第一部分是降序排列的分数,第二部分是每个分数对应的排名。

第一部分不难写:

select a.Score as Score
from Scores a
order by a.Score DESC
比较难的是第二部分。假设现在给你一个分数X,如何算出它的排名Rank呢?
我们可以先提取出大于等于X的所有分数集合H,将H去重后的元素个数就是X的排名。比如你考了99分,但最高的就只有99分,那么去重之后集合H里就只有99一个元素,个数为1,因此你的Rank为1。
先提取集合H:

select b.Score from Scores b where b.Score >= X;
我们要的是集合H去重之后的元素个数,因此升级为:

select count(distinct b.Score) from Scores b where b.Score >= X as Rank;
而从结果的角度来看,第二部分的Rank是对应第一部分的分数来的,所以这里的X就是上面的a.Score,把两部分结合在一起为:

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 a.Score DESC

作者:johnbear007
链接:https://leetcode-cn.com/problems/rank-scores/solution/fen-cheng-liang-ge-bu-fen-xie-hui-rong-yi-hen-duo-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

Published 23 original articles · praised 0 · visits 137

Guess you like

Origin blog.csdn.net/qq_35683407/article/details/105424473