题目描述
编写一个 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 |
+-------+------+
算法设计与分析:
- 首先是我们要理解分数的排名的目的,条件:两个分数的排名(Rank)相同,也就是说如果班级上有50个同学,全部的考分都是一样的,那么就只有一个排名(第一名);如果考分只有90和80分的,那么就只有两个排名(第一名和第二名)。[排名和人数无关]
- 那么我们就将考分去重统计就可以知道有几个排名了
- 那么我们是不是可以这样考虑:当前的分数在班上排名第几,只要统计(去重)比我大的分数的个数就是我的排名。
1、将分数按照降序排序:select a.Score as score from Scores a order by Score DESC;
2、需要统计(去重)比我大的分数的个数就是我的排名:select count(distinct b.Score) from Scores b where b.Score >= 我的分数
3、结合:
select a.Score as score, (select count(distinct b.Score) from Scores b where b.Score=a.Score) as rank from Scores a order by Score DESC;
# select a.Score from Scores a order by Score DESC;
# select count(distinct b.Score) as Rank from Scores b order by Score DESC; # 总共有4种分数
# select count(distinct b.Score) as Rank from Scores b where b.Score >= 我的分数 ;
select a.Score, (select count(distinct b.Score) from Scores b where b.Score >= a.Score) as Rank from Scores a order by Score DESC;