原题:https://leetcode-cn.com/problems/department-top-three-salaries/
我自己做leetcode的数据库题目的解题记录:
解题目录 https://blog.csdn.net/weixin_42845682/article/details/105196004
这道题很有意思,建议参考一下: 184. 部门工资最高的员工
https://blog.csdn.net/weixin_42845682/article/details/105437193
突然发现,这道题在leetcode的难度是困难呢。有点意思嘿。
题目描述:
Employee 表包含所有员工信息,每个员工有其对应的工号 Id,姓名 Name,工资 Salary 和部门编号 DepartmentId 。
+----+-------+--------+--------------+
| Id | Name | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1 | Joe | 85000 | 1 |
| 2 | Henry | 80000 | 2 |
| 3 | Sam | 60000 | 2 |
| 4 | Max | 90000 | 1 |
| 5 | Janet | 69000 | 1 |
| 6 | Randy | 85000 | 1 |
| 7 | Will | 70000 | 1 |
+----+-------+--------+--------------+
Department 表包含公司所有部门的信息。
+----+----------+
| Id | Name |
+----+----------+
| 1 | IT |
| 2 | Sales |
+----+----------+
编写一个 SQL 查询,找出每个部门获得前三高工资的所有员工。例如,根据上述给定的表,查询结果应返回:
+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT | Max | 90000 |
| IT | Randy | 85000 |
| IT | Joe | 85000 |
| IT | Will | 70000 |
| Sales | Henry | 80000 |
| Sales | Sam | 60000 |
+------------+----------+--------+
解释:
IT 部门中,Max 获得了最高的工资,Randy 和 Joe 都拿到了第二高的工资,Will 的工资排第三。销售部门(Sales)只有两名员工,Henry 的工资最高,Sam 的工资排第二。
答案:
第一种答案
根据题目描述和参考的那篇文章,直接把使用dense_rank()的sql抄过来,把最后的=1换成 <=3 就完事。
select
dname department,
ename employee,
salary
from(
select
d.name dname,
e.name ename,
e.salary,
dense_rank() over(partition by d.name order by salary desc) row_num
from employee e
join department d on e.departmentId=d.id
) tmp
where row_num <=3
为什么执行的这么慢呢?
第二种答案
万一用的是mysql,不支持dense_rank()咋办呢?(听说mysql8.0支持over()了。)
select
d.name Department,
e.name Employee,
e.salary Salary
from employee e
join department d on e.departmentid = d.id
where 3>
(
select
count(distinct(e2.salary))
from employee e2
where e.departmentid=e2.departmentid
and e2.salary > e.salary
)
一开始写的时候,where后面的筛选条件写成了3>=…,结果出现了部门前四高的工资,一时半会有点没想通。后来想通了:假设部门前三高是30000,20000,10000,那么比30000高的只有0个,那么比20000高的只有1个,那么比10000高的只有2个。
select
d.name Department,
e.name Employee,
e.salary Salary
from employee e
join department d on e.departmentid = d.id
where 3>=
(
select
count(distinct(e2.salary))
from employee e2
where e.departmentid=e2.departmentid
and e2.salary >= e.salary
)
虽然这两个sql基本一模一样,但我还是喜欢这种写法。。。
ps:希望我永远不用写这种sql。