宇筱博客

  • 解决办法
  • 学无止境
  • 记录时光
  • 百宝箱
宇筱博客
点滴记忆,汇聚成海。
  1. 首页
  2. 解决办法
  3. 正文

MySQL为查询结果添加序号

2020年1月1日 638点热度 0人点赞 0条评论

查询结果

现在的要求是:根据salary的值排名,并添加序号。

有三种添加序号的方式:

    1、顺序排名

    2、顺序排名,有相同的salary采取并列,保持排名不变

    3、顺序排名,采取并列,且排名不变的salary仍然占用一个位置

一、不考虑并列( “:=”表示赋值)

select
s.emp_no,s.salary,
@n:=@n+1 rank
from salaries s, (select @n:= 0) d
where s.to_date='9999-01-01' order by s.salary desc

查询结果

在这里插入图片描述

二、采取并列(需要添加一个字段来保存上一次的salary值进行比较,如果相同,排名不变;如果不同,排名+1)

select
s.emp_no,s.salary,
case
when @t=s.salary then @n
when @t:=s.salary then @n:=@n+1
end rank
from salaries s, (select @n:= 0,@t:= -1) d
where s.to_date='9999-01-01' order by s.salary desc

还有一种简便写法

SELECT emp_no,salary,
@rank := @rank + (@pre <> (@pre := salary)) Rank
FROM salaries, (SELECT @rank := 0, @pre := -1) INIT
WHERE to_date = '9999-01-01
order by salary

查询结果

在这里插入图片描述

三、顺序排名,采取并列,且排名不变的salary仍然占用一个位置

select
s.emp_no,s.salary,@a:=@a+1,@n:=
case
when @t=s.salary then @n
when @t:=s.salary then @n:=@a
end rank
from salaries s, (select @n:= 0,@t:= -1,@a:= 0 ) d
where s.to_date='9999-01-01' order by s.salary asc

查询结果

在这里插入图片描述

原文链接:https://blog.csdn.net/weixin_42383575/article/details/85090168

标签: 暂无
最后更新:2020年1月1日

小渔民

这个人很懒,什么都没留下

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2025 宇筱博客. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

豫ICP备15017825号-2