題目描述
編寫一個 SQL 查詢來實現分數排名。如果兩個分數相同,則兩個分數排名(Rank)相同。請注意,平分後的下一個名次應該是下一個連續的整數值。換句話說,名次之間不應該有“間隔”
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/rank-scores
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
select Score, (select count(distinct s.Score) from Scores as s where s.Score >= Scores.Score) as Rank from Scores order by Score desc;
答案解析
# 獲取分數列
select Score,
# 獲取去重分數個數,需要先執行from後面的條件,根據後面的條件獲取數量
(select count(distinct s.Score)
# 將獲取到的每一個Score跟所有的Score做比較,比較大的會進行去重,也就是上一句的distinct
from Scores as s where s.Score >= Scores.Score)
# 進行倒序排
as Rank from Scores order by Score desc;