編寫一個 SQL 查詢來實現分數排名。sql
若是兩個分數相同,則兩個分數排名(Rank)相同。請注意,平分後的下一個名次應該是下一個連續的整數值。換句話說,名次之間不該該有「間隔」。code
+----+-------+ | Id | Score | +----+-------+ | 1 | 3.50 | | 2 | 3.65 | | 3 | 4.00 | | 4 | 3.85 | | 5 | 4.00 | | 6 | 3.65 | +----+-------+
例如,根據上述給定的 Scores
表,你的查詢應該返回(按分數從高到低排列):ip
+-------+------+ | Score | Rank | +-------+------+ | 4.00 | 1 | | 4.00 | 1 | | 3.85 | 2 | | 3.65 | 3 | | 3.65 | 3 | | 3.50 | 4 | +-------+------+
重要提示: 對於 MySQL 解決方案,若是要轉義用做列名的保留字,能夠在關鍵字以前和以後使用撇號。例如 `Rank`it
# Write your MySQL query statement below SELECT Score, DENSE_RANK() OVER(ORDER BY Score DESC) AS `Rank` FROM Scores;
DENSE_RANK、RANK、ROW_NUMBER 的使用說明io
Function | Description |
---|---|
DENSE_RANK | 並列連續排名 |
RANK | 並列跳躍排名 |
ROW_NUMBER | 連續排名 |
eg.table
-------------------------------------------------------- -- 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 | -- +----+-------+------------+------+------------+ --------------------------------------------------------