SQL 185. 部门工资前三高的所有员工

SQL 185. 部门工资前三高的所有员工

题目 : https://leetcode.cn/problems/department-top-three-salaries/

数据

drop table Employee;
drop table Department;

Create table If Not Exists Employee (
  id int, 
  name varchar(255) comment '姓名', 
  salary int comment '工资', 
  departmentId int comment '部门id'
);

Create table If Not Exists Department (
  id int, 
  name varchar(255) comment '部门名'
);

insert into Employee (id, name, salary, departmentId) values ('1', 'Joe', '85000', '1');
insert into Employee (id, name, salary, departmentId) values ('2', 'Henry', '80000', '2');
insert into Employee (id, name, salary, departmentId) values ('3', 'Sam', '60000', '2');
insert into Employee (id, name, salary, departmentId) values ('4', 'Max', '90000', '1');
insert into Employee (id, name, salary, departmentId) values ('5', 'Janet', '69000', '1');
insert into Employee (id, name, salary, departmentId) values ('6', 'Randy', '85000', '1');
insert into Employee (id, name, salary, departmentId) values ('7', 'Will', '70000', '1');

insert into Department (id, name) values ('1', 'IT');
insert into Department (id, name) values ('2', 'Sales');

需求

查询每个部门工资中排名前三的员工

查询结果 :

| Department | Employee | Salary |
| IT         | Max      | 90000  |
| IT         | Joe      | 85000  |
| IT         | Randy    | 85000  |
| IT         | Will     | 70000  |
| Sales      | Henry    | 80000  |
| Sales      | Sam      | 60000  |

解决

with t1 as (
  select departmentId,
    name,
    salary,
    dense_rank() over(partition by departmentId order by salary desc) as rk
  from Employee
),
t2 as (
  select departmentId,
    name,
    salary
  from t1
  where rk <= 3
)
select t3.name as Department,
  t2.name as Employee,
  t2.salary as Salary
from t2 join Department t3
  on t2.departmentId = t3.id;

猜你喜欢

转载自blog.csdn.net/qq_44226094/article/details/130067098