題目描述
編寫一個 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 |
+-------+------+
算法設計與分析:
- 首先是我們要理解分數的排名的目的,條件:兩個分數的排名(Rank)相同,也就是說如果班級上有50個同學,全部的考分都是一樣的,那麼就只有一個排名(第一名);如果考分只有90和80分的,那麼就只有兩個排名(第一名和第二名)。[排名和人數無關]
- 那麼我們就將考分去重統計就可以知道有幾個排名了
- 那麼我們是不是可以這樣考慮:當前的分數在班上排名第幾,只要統計(去重)比我大的分數的個數就是我的排名。
1、將分數按照降序排序:select a.Score as score from Scores a order by Score DESC;
2、需要統計(去重)比我大的分數的個數就是我的排名:select count(distinct b.Score) from Scores b where b.Score >= 我的分數
3、結合:
select a.Score as score, (select count(distinct b.Score) from Scores b where b.Score=a.Score) as rank from Scores a order by Score DESC;
# select a.Score from Scores a order by Score DESC;
# select count(distinct b.Score) as Rank from Scores b order by Score DESC; # 總共有4種分數
# select count(distinct b.Score) as Rank from Scores b where b.Score >= 我的分數 ;
select a.Score, (select count(distinct b.Score) from Scores b where b.Score >= a.Score) as Rank from Scores a order by Score DESC;