leetcode MYSQL数据库题目178

本文介绍了一个SQL查询案例,用于对分数进行排名,并处理分数相同时的排名问题。通过使用子查询和distinct关键字,实现了对成绩表中分数的有效排序。

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

178. Rank Scores

1、题目与答案

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.

编写SQL查询对分数进行排序。如果两个分数相等,则两者应具有相同的排名。请注意,在相等之后,下一个排名数应该是下一个连续的整数值。换句话说,相等的分数并列。
Table:Scores

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

For example, given the above Scores table, your query should generate the following report (order by highest score):

例如,给定上面的“Scores”表,您的查询应生成以下报告(按最高分数排序)

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

答案:
select
Score,
(select count(distinct b.Score) from scores b where b.Score >= s.Score) as Rank
from scores s
order by Score desc


2、 知识点总结

验证步骤:

创建并插入表scores
create table scores(
Id int NULL,
Score double NULL
);
insert into scores
values(1,3.5),(2,3.65),(3,4.00),(4,3.85),(5,4.00),(6,3.65);

执行答案可得:

+-------+------+
| Score | Rank |
+-------+------+
|     4 |    1 |
|     4 |    1 |
|  3.85 |    2 |
|  3.65 |    3 |
|  3.65 |    3 |
|   3.5 |    4 |
+-------+------+
6 rows in set (0.00 sec)

知识点:

  • 子查询与where筛选
  • select count( distinct id ) from table_name 计算talbebname表中id不同的记录有多少条
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值