[leetCode]分?jǐn)?shù)排名

sql架構(gòu):

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')
編寫一個(gè) SQL 查詢來實(shí)現(xiàn)分?jǐn)?shù)排名。如果兩個(gè)分?jǐn)?shù)相同,則兩個(gè)分?jǐn)?shù)排名(Rank)相同。請(qǐng)注意,平分后的下一個(gè)名次應(yīng)該是下一個(gè)連續(xù)的整數(shù)值。換句話說,名次之間不應(yīng)該有“間隔”。

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

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

解決方法一:

/*此處as Rank會(huì)報(bào)錯(cuò)  應(yīng)該是因?yàn)镽ank為關(guān)鍵字*/
select Score,(select count(DISTINCT Score) from Scores where Score >= s.Score) as Rank
from Scores s
order by Score desc;

DISTINCT的用法

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

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

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容