題目如下
編寫一個 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`
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/rank-scores
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
解題思路
需要求得的結果分爲兩列,第一列爲Score
,可用order by
排序得到,第二列可以通過大於某個分數的人數(去除重複的分數)得到。
第一列
select s1.Score from Scores s1 order by s1.Score
第二列
這一列的獲取主要是能夠理解,舉個例子:有分數爲(100,98,98,97…)幾個分數,要獲取97分的排名,只要將所有分數去重(discinct score
),然後統計大於等於97分的人數即可。
select count(distinct Score) from Score s2 where s2.Score>=x
x爲上面第一列中每個學生的成績。
第一列第二列合併
select s1.Score,(select count(distinct Score) from Scores s2 where s2.Score>=s1.Score) AS 'Rank' from Scores s1 order by Score DESC