1. 程式人生 > >【LeetCode--資料庫】分數排名

【LeetCode--資料庫】分數排名

178Rank Scores(中等)

題目:編寫一個sql語句來實現分數排名,如果兩個分數相同,則兩個分數排名(Rank)相同,而且下一個名次應該是下一個連續的整數值,也就是說,名次之間不能有間隔。

+----+-------+
| Id | Score |
+----+-------+
| 1  | 3.50  |
| 2  | 3.65  |
| 3  | 4.00  |
| 4  | 3.85  |
| 5  | 4.00  |
| 6  | 3.65  |
+----+-------+

期望結果如下:

+-------+------+
| Score | Rank |
+-------+------+
| 4.00  | 1    |
| 4.00  | 1    |
| 3.85  | 2    |
| 3.65  | 3    |
| 3.65  | 3    |
| 3.50  | 4    |
+-------+------+

解法一:對於每一個分數,從表中找出有多少個大於或等於該分數的不重複分數,然後降序排列

select Score,
(select count(distinct Score) from Scores as s2 where s2.Score >= s1.Score) Rank 
from Scores as s1
order by Score DESC;

解法二:使用聯結 join,條件是左表的分數小於等於右表的分數時,對右表的分數進行計數(即計算有幾個不重複的分數大於自己,計算結果就是rank),然後根據id分組後,再根據分數降序排列

select s1.Score, count(distinct s2.Score) Rank
from Scores as s1 join Scores as s2 on s1.Score <= s2.Score
group by s1.Id 
order by s1.Score DESC;