SQL处理排行榜问题

简介: SQL处理排行榜问题

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.然后再查出某一名次的学生

/*
 进行排名,相同的分数应该是同名次
 */
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月前
|
SQL
leetcode-SQL-1407. 排名靠前的旅行者
leetcode-SQL-1407. 排名靠前的旅行者
43 1
|
3月前
|
SQL 分布式计算 NoSQL
【SQL 审核查询平台】Archery使用介绍
【SQL 审核查询平台】Archery使用介绍
288 0
【SQL 审核查询平台】Archery使用介绍
|
3月前
|
SQL 数据库
三、SQL的基础查询
三、SQL的基础查询
38 0
|
9月前
|
SQL 算法 JavaScript
在线就能用的 SQL 练习平台(附SQL学习文档)
在线就能用的 SQL 练习平台(附SQL学习文档)
364 0
|
SQL Oracle Java
【SQL开发实战技巧】系列(三):SQL排序的那些事
如何以指定的单列或多列顺序返回查询结果、通过translate函数替换字符串、如何根据数字和字母混合字符串中的字母排序以及空值排序。【SQL开发实战技巧】这一系列博主当作复习旧知识来进行写作,毕竟SQL开发在数据分析场景非常重要且基础,面试也会经常问SQL开发和调优经验,相信当我写完这一系列文章,也能再有所收获,未来面对SQL面试也能游刃有余~。不早了,零点十分了,又是一篇SQL基础文章,继续加油!温故而知新~
【SQL开发实战技巧】系列(三):SQL排序的那些事
|
SQL 机器学习/深度学习 关系型数据库
【SQL刷题】Day7----SQL检索数据专项练习
【SQL刷题】Day7----SQL检索数据专项练习
110 0
【SQL刷题】Day7----SQL检索数据专项练习
|
SQL 关系型数据库 MySQL
教你用SQL实现统计排名
在某些应用场景中,我们经常会遇到一些排名的问题,比如按成绩或年龄排名。排名也有多种排名方式,如直接排名、分组排名,排名有间隔或排名无间隔等等,这篇文章将总结几种MySQL中常见的排名问题。
623 0