[leetCode]分數(shù)排名

sql架構:

Create table If Not Exists Scores (Id int, Score DECIMAL(3,2))
Truncate table Scores
insert into Scores (Id, Score) values ('1', '3.5')
insert into Scores (Id, Score) values ('2', '3.65')
insert into Scores (Id, Score) values ('3', '4.0')
insert into Scores (Id, Score) values ('4', '3.85')
insert into Scores (Id, Score) values ('5', '4.0')
insert into Scores (Id, Score) values ('6', '3.65')
編寫一個 SQL 查詢來實現(xiàn)分數(shù)排名。如果兩個分數(shù)相同,則兩個分數(shù)排名(Rank)相同。請注意,平分后的下一個名次應該是下一個連續(xù)的整數(shù)值。換句話說,名次之間不應該有“間隔”。

+----+-------+
| Id | Score |
+----+-------+
| 1  | 3.50  |
| 2  | 3.65  |
| 3  | 4.00  |
| 4  | 3.85  |
| 5  | 4.00  |
| 6  | 3.65  |
+----+-------+
例如,根據(jù)上述給定的 Scores 表,你的查詢應該返回(按分數(shù)從高到低排列):

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

解決方法一:

/*此處as Rank會報錯  應該是因為Rank為關鍵字*/
select Score,(select count(DISTINCT Score) from Scores where Score >= s.Score) as Rank
from Scores s
order by Score desc;

DISTINCT的用法

在使用MySQL時,有時需要查詢出某個字段不重復的記錄,這時可以使用mysql提供的distinct這個關鍵字來過濾重復的記錄,但是實際中我們往往用distinct來返回不重復字段的條數(shù)(count(distinct id)),其原因是distinct只能返回他的目標字段,而無法返回其他字段

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容