【Leetcode】Mysql分数排名

编写一个 SQL 查询来实现分数排名。如果两个分数相同,则两个分数排名(Rank)相同。请注意,平分后的下一个名次应该是下一个连续的整数值。换句话说,名次之间不应该有“间隔”。

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

例如,根据上述给定的 Scores 表,你的查询应该返回(按分数从高到低排列):

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

引用大佬的建表语句,方便测试自己的猜想:

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');  

查询去重后分数的,条件:当前行分数大于等于同表的分数的count数量,去重显示,然后降序输出

# 方法一:
# select Score, (select count(distinct Score) from Scores where Score>=s.Score) as Rank from Scores as s order by Score desc;  

首先查找去重后的分数作为新表,使用count统计行,条件:当前去重表后的分数>=未去重的分数作为Rank的参数,然后使用排序降序输出

# 方法二:
select Score,(select count(*) from (select distinct Score as s from Scores) as new_scores where s >= Score) Rank from Scores order by Score desc;

猜你喜欢

转载自blog.csdn.net/chenhua1125/article/details/80343199