178、分数排名--leetcode

题目描述

编写一个 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;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值