0
点赞
收藏
分享

微信扫一扫

SQL处理排行榜问题

迪莉娅1979 2022-03-12 阅读 38

小闫辛苦码了 1604 个字 

文章可能占用您 5 分钟 

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


今日分享

SQL处理排行榜问题_公众号小闫同学pythonnote.cn查看:​13144​回复:​541​Setting goals is the first step in turning the invisible into the visible.

——  Tony Robbins

SQL处理排行榜问题_python_02

1.面试题

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

SQL处理排行榜问题_数据_03

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;

SQL处理排行榜问题_公众号_04

/*
进行排名,相同的分数应该是同名次
*/
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;

SQL处理排行榜问题_python_05




排版:小闫

图片素材:小闫

文案:小闫

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


举报

相关推荐

问题 C: 销售排行榜

CSS 排行榜

HTTP分数排行榜

OJ解题排行榜

jQuery电影排行榜

分享---GitHub中文排行榜

0 条评论