在mysql中进行统计排序(跳跃排序和连续排序)

本文介绍在MySQL数据库中如何实现跳跃排序和连续排序,通过具体SQL语句演示如何处理并列名次情况下的排序问题,适用于需要精确控制排名显示的应用场景。

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

-- 在mysql中进行统计排序(跳跃排序和连续排序)
CREATE TABLE `tb_score` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `score` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`)

select * from tb_score;

delete from tb_score where id > 0;
commit;

insert into tb_score (score) values(43),(22),(22),(18);
commit;

-- 跳跃排序,有并列名次的情况下,整个排序序号不连续
-- 将原表添加一列自增序号的列,然后按照数字进行分组,取得最小的自增序号,在最外层按照各自的最小序号排序
select z.*, x.min_cnt from tb_score z,
(
select score, min(cnt) min_cnt from (
(select id, score,  (@i:=@i+1) cnt from tb_score, (SELECT @i:=0) as i  order by score ) ) a
group by score ) x
where z.score = x.score
order by x.min_cnt;

-- 连续排序,有并列名次的情况下,整个排序序号是连续
-- 将原表对数字进行分组并排序,然后将其做为一个子表,在上面添加一个自增的序号
select * from tb_score t , (
select tmp.score,  (@i:=@i+1) rank from (
select score  from tb_score  
group by score order by score asc ) tmp,(SELECT @i:=0) as i ) b
where t.score = b.score
order by b.rank;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值