LeetCode178. Rank Scores - 分数排名 <Medium>

本文介绍如何使用SQL查询实现分数排名,当出现相同分数时确保排名一致,并且在排名间没有空缺。提供两种方法实现这一目标,适用于MySQL数据库。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

编写一个 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    |
+-------+------+

重要提示:对于 MySQL 解决方案,如果要转义用作列名的保留字,可以在关键字之前和之后使用撇号。例如 `Rank`

Write a SQL query to rank scores. If there is a tie between two scores, both should have the same ranking. Note that after a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no "holes" between ranks.
For example, given the above Scores table, your query should generate the following report (order by highest score):
Important Note: For MySQL solutions, to escape reserved words used as column names, you can use an apostrophe before and after the keyword. For example `Rank`.

分析题意:查询Score、Rank,按分数降序 且 Rank在Score不同时自动递增

有如下思路:

1、两个Score表a、b,左表a 左连接 右表b(相同表a、b左连接等同于内交;此外,Mysql中 join == inner join == cross join 详情点击 ,此时相同表内交,left join效果也一样),右表分数>=左表,分组按分数降序排列;

2、对于每一个分数,使用临时表,找出表中比该分数值大的个数,按分数降序排列;

# Method 1
SELECT a.Score, COUNT(DISTINCT b.Score) `Rank`
FROM Scores a JOIN Scores b ON a.Score <= b.Score
GROUP BY a.Id 
ORDER BY a.Score DESC;
# Method 2
select a.Score,(select count(distinct Score) from Scores where 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、付费专栏及课程。

余额充值