SQL 178. 分数排名

SQL 178. 分数排名

题目 : https://leetcode.cn/problems/rank-scores/

数据

Create table If Not Exists Scores (
  id int comment '主键', 
  score DECIMAL(3,2) comment '分数'
);

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

需求

查询对分数进行排序

排名规则:

  • 分数应按从高到低排列
  • 如果两个分数相等,那么两个分数的排名应该相同
  • 在排名相同的分数后,排名数应该是下一个连续的整数。换句话说,排名之间不应该有空缺的数字
  • 按 score 降序返回结果表

查询结果 :

| score | rank |
| 4.00  | 1    |
| 4.00  | 1    |
| 3.85  | 2    |
| 3.65  | 3    |
| 3.65  | 3    |
| 3.50  | 4    |

解决

技术点 :

  • row_number() : 同值不同名,类似行号,如 : 3000、2000、2000、1000 , 排名 : 1、2、3、4
  • rank() : 同值同名,有跳级,如 : 3000、2000、2000、1000 , 排名 : 1、2、2、4
  • dense_rank() : 同值同名,无跳级,如 : 3000、2000、2000、1000 , 排名 : 1、2、2、3
select score,
  dence_rank() over(order by score desc) as rank
from Scores
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值