前言
练习sql语句,所有题目来自于力扣(https://leetcode.cn/problemset/database/)的免费数据库练习题。
今日题目:
185.部门工资前三高的所有员工
表:Employee
列名 | 类型 |
---|---|
id | int |
name | varchar |
salary | int |
departmentId | int |
id 是该表的主键列(具有唯一值的列)。
departmentId 是 Department 表中 ID 的外键(reference 列)。该表的每一行都表示员工的ID、姓名和工资。它还包含了他们部门的ID。
表:Department
列名 | 类型 |
---|---|
id | int |
name | varchar |
id 是该表的主键列(具有唯一值的列)。
该表的每一行表示部门ID和部门名。
公司的主管们感兴趣的是公司每个部门中谁赚的钱最多。一个部门的 高收入者 是指一个员工的工资在该部门的 不同 工资中 排名前三 。
编写解决方案,找出每个部门中 收入高的员工 。
我那不值一提的想法:
- 首先梳理表内容,题干一共给了两张表,一张员工表,一张部门表,员工表记录了员工id,员工姓名,薪水以及部门id,部门表记录了部门id,以及部门名
- 其次分析需求,需要找到各部门薪水排名前三的员工
- 对于这道题,我的思路是需要先找到薪水排名前三的薪水,然后再和员工表想连接,连接条件就是部门id
- 要找到排名前三的薪水,这里使用dense_rank对于薪水进行排序,同时对于相同的薪水,编号不会跳过,是一样的
with tem_3 as (
select *
from(
select departmentId,name,Salary,dense_rank() over(partition by departmentId order by salary desc) as "num"
from Employee
) as a
where num = 1 or num =2 or num = 3
)
- 然后再连接部门表就能得到结果
select d.name as Department,t.name as Employee,t.Salary
from tem_3 t
left join Department d
on t.departmentId = d.id
- 完整代码
with tem_3 as (
select *
from(
select departmentId,name,Salary,dense_rank() over(partition by departmentId order by salary desc) as "num"
from Employee
) as a
where num = 1 or num =2 or num = 3
)
select d.name as Department,t.name as Employee,t.Salary
from tem_3 t
left join Department d
on t.departmentId = d.id
结果:
总结:
能运行就行。