SQL23 对所有员工的当前薪水按照salary进行按照1-N的排名

本文最后更新于:2022年4月9日 中午


题目描述

对所有员工的当前(to_date=’9999-01-01’)薪水按照salary进行按照1-N的排名,相同salary并列且按照emp_no升序排列

1
2
3
4
5
6
CREATE TABLE `salaries` (
`emp_no` int(11) NOT NULL,
`salary` int(11) NOT NULL,
`from_date` date NOT NULL,
`to_date` date NOT NULL,
PRIMARY KEY (`emp_no`,`from_date`));

输入描述

输出描述

emp_no salary rank
10005 94692 1
10009 94409 2
10010 94409 2
10001 88958 3
10007 88070 4
10004 74057 5
10002 72527 6
10003 43311 7
10006 43311 7
10011 25828 8

题解

1
2
3
4
5
6
7
select emp_no, salary, dense_rank() over (order by salary desc) as rank from salaries
where to_date='9999-01-01'

select a.emp_no,a.salary,count(distinct b.salary) from salaries as a join salaries as b
where a.to_date='9999-01-01' and b.to_date='9999-01-01' and a.salary<=b.salary
group by a.emp_no
order by a.salary desc, a.emp_no asc

备注:

  1. 方法一:利用dense_rank()函数

    关于MySQL中 rank()、row_number()、dense_rank()排序

    这些函数是在MySQL8.0以后的版本中才有的;

    区别:(示例根据 score 排序)

  2. 方法二:方法原理与 [SQL18](https://ronnyz.gitee.io/2020/08/11/SQL18 查找当前薪水排名第二多的员工,不使用order by/) 有相似

    表的自连接条件是第一个关键点 a.salary<=b.salary;其次进行count统计时,由于有重复的数据,结合distinct筛选大于等于该条 salary 的数据条数;最后输出结果有两个排序条件。

    参考:[「只是」最辣的那棵「韭菜」而已] 同学的解答

参考文章:

https://blog.csdn.net/sqsltr/article/details/94408487