【SQL刷题系列】:leetcode178 Rank Scores

▌题目描述app


Write a SQL query to rank scores. If there is a tie between two scores, both should have the same ranking. Note that after a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no "holes" between ranks.ide

编写一个 SQL查询来对分数排名。若是两个分数相同,那么两个分数应该有一样的排名。但也请注意,若是平分,那么下一个名次应该是下一个连续的整数值。换句话说,名次之间没有“间隔”。spa


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


例如,若是给你上面 Scores 表,你的查询结果应该与下面这样相同(分数从高到低排列)。code


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


▌参考答案orm


SELECT Score, 
    (
        SELECT COUNT(DISTINCT b.Score) + 1 
        FROM Scores AS b 
        WHERE b.Score > Scores.Score 
        LIMIT 1
    ) AS Rank 
FROM Scores order by Rank ;


▌答案解析排序


上面参考答案的思路是:利用表自链接。当查询表的每一个分数时,都查找比这个分数大的其它分数的个数(不含重复值),而后在这个个数上加1,最后获得的个数就是每一个分数的rank。最后用order by将rank排序便可。逻辑上有点相似于两个for的嵌套循环。ci

相关文章
相关标签/搜索