SQL处理排行榜问题

小闫辛苦码了 1604 个字 

文章可能占用您 5 分钟 

欢迎关注「全栈技术精选」

今日分享

小闫同学pythonnote.cn

查看:13144回复:541

Setting goals is the first step in turning the invisible into the visible.

——  Tony Robbins

对现有的数据,根据某一字段进行排名,如果没有 RANK 函数,SQL 语句怎么写?接下来就分享一道面试题......更多精彩文章请关注公众号『Pythonnote』或者『全栈技术精选』

1.面试题

现在有一张表,保存着学生的相关信息(id 、名字以及分数),如下图所示。请写出 sql 语句查询排名第4的学生信息。

2.答案

/*
 进行排名,相同的分数同名次
 */
select *
from (select name,
             score,
            (case when @p=score then @r
                  when @p:=score then @r:=@r+1 end) as stu_rank
        from tb_student, (select @r:=0,@p:=NULL) r
       order by score desc) v_rank
where v_rank.stu_rank=4;

此语句为小闫参考网络类似案例后所写,可以达到预期效果,但在性能或者复杂度上可能有所欠缺,如果您有更好的方法,请关注公众号「全栈技术精选」后台给我留言吧

3.分析

3.1 准备数据

在讲解之前,先让我们创建一个测试数据库 testdb,然后创建一张测试用表 tb_student

use testdb;


create table tb_student(
    id int auto_increment primary key,
    name varchar(10),
    score int
);

然后按照图片中的信息进行构造数据:

insert into tb_student(name, score) values('小三', 1000);
insert into tb_student(name, score) values('jack', 99);
insert into tb_student(name, score) values('rose', 10);
insert into tb_student(name, score) values('马蓉', 8);
insert into tb_student(name, score) values('李小璐', 40);
insert into tb_student(name, score) values('fuck', 300);
insert into tb_student(name, score) values('李小璐2', 40);
insert into tb_student(name, score) values('李小璐3', 40);

3.2 知识点

赋值号:=

条件语句case when

3.3 过程

1.首先需要根据分数进行排名(分数相同的同学,名次应该也是相同的,并列关系)

select name,
       score,
      (case when @p=score then @r
            when @p:=score then @r:=@r+1 end) as stu_rank
from tb_student, (select @r:=0,@p:=NULL) as r
order by score desc;

2.然后再查出某一名次的学生更多精彩文章请关注公众号『Pythonnote』或者『全栈技术精选』

/*
 进行排名,相同的分数应该是同名次
 */
select *
from (select name,
             score,
            (case when @p=score then @r
                  when @p:=score then @r:=@r+1 end) as stu_rank
        from tb_student, (select @r:=0,@p:=NULL) r
       order by score desc) v_rank
where v_rank.stu_rank=4;

排版:小闫

图片素材:小闫

文案:小闫

长按扫描下方二维码即刻关注小闫

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值