▌題目描述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