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)字段,而無法返回其他字段