题目描述
编写一个 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 |
+-------+------+
重要提示: 对于 MySQL 解决方案,如果要转义用作列名的保留字,可以在关键字之前和之后使用撇号。例如 `Rank`
题解
# Write your MySQL query statement below
SELECT
Score,
DENSE_RANK() OVER(ORDER BY Score DESC) AS `Rank`
FROM
Scores;
DENSE_RANK、RANK、ROW_NUMBER 的使用说明
Function
Description
DENSE_RANK
并列连续排名
RANK
并列跳跃排名
ROW_NUMBER
连续排名
eg.
--------------------------------------------------------
-- table_name: Scores
--
-- +----+-------+
-- | id | score |
-- +----+-------+
-- | 1 | 78 |
-- | 2 | 89 |
-- | 3 | 86 |
-- | 4 | 91 |
-- | 5 | 78 |
-- | 6 | 89 |
-- | 7 | 89 |
-- +----+-------+
--------------------------------------------------------
--------------------------------------------------------
SELECT
id,
score,
DENSE_RANK() OVER(ORDER BY score DESC) AS `DENSE_RANK`,
RANK() OVER(ORDER BY score DESC) AS `RANK`,
ROW_NUMBER() OVER(ORDER BY score DESC) AS `ROW_NUMBER`
FROM
Scores;
--------------------------------------------------------
--------------------------------------------------------
-- result:
--
-- +----+-------+------------+------+------------+
-- | id | score | DENSE_RANK | RANK | ROW_NUMBER |
-- +----+-------+------------+------+------------+
-- | 4 | 91 | 1 | 1 | 1 |
-- | 2 | 89 | 2 | 2 | 2 |
-- | 6 | 89 | 2 | 2 | 3 |
-- | 7 | 89 | 2 | 2 | 4 |
-- | 3 | 86 | 3 | 5 | 5 |
-- | 1 | 78 | 4 | 6 | 6 |
-- | 5 | 78 | 4 | 6 | 7 |
-- +----+-------+------------+------+------------+
--------------------------------------------------------