前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SQL处理排行榜问题

SQL处理排行榜问题

作者头像
小闫同学啊
发布2020-05-26 17:23:38
6850
发布2020-05-26 17:23:38
举报
文章被收录于专栏:小闫笔记小闫笔记

今日分享

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

—— Tony Robbins

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

1.面试题

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

2.答案

代码语言:javascript
复制
/* 进行排名,相同的分数同名次 */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_rankwhere v_rank.stu_rank=4;

3.分析

3.1 准备数据

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

代码语言:javascript
复制
use testdb;
create table tb_student(    id int auto_increment primary key,    name varchar(10),    score int);

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

代码语言:javascript
复制
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.首先需要根据分数进行排名(分数相同的同学,名次应该也是相同的,并列关系)

代码语言:javascript
复制
select name,       score,      (case when @p=score then @r            when @p:=score then @r:=@r+1 end) as stu_rankfrom tb_student, (select @r:=0,@p:=NULL) as rorder by score desc;

2.然后再查出某一名次的学生

代码语言:javascript
复制
/* 进行排名,相同的分数应该是同名次 */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_rankwhere v_rank.stu_rank=4;
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-05-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 全栈技术精选 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.面试题
  • 2.答案
    • 3.1 准备数据
      • 3.2 知识点
        • 3.3 过程
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档