目录
题目
一家公司想雇佣新员工。公司的工资预算是 70000
美元。公司的招聘标准是:
- 雇佣最多的高级员工。
- 在雇佣最多的高级员工后,使用剩余预算雇佣最多的初级员工。
编写一个SQL查询,查找根据上述标准雇佣的高级员工和初级员工的数量。
按 任意顺序 返回结果表。
准备数据
Create table If Not Exists Candidates (employee_id int, experience ENUM('Senior', 'Junior'), salary int)
Truncate table Candidates
insert into Candidates (employee_id, experience, salary) values ('1', 'Junior', '10000')
insert into Candidates (employee_id, experience, salary) values ('9', 'Junior', '10000')
insert into Candidates (employee_id, experience, salary) values ('2', 'Senior', '20000')
insert into Candidates (employee_id, experience, salary) values ('11', 'Senior', '20000')
insert into Candidates (employee_id, experience, salary) values ('13', 'Senior', '50000')
insert into Candidates (employee_id, experience, salary) values ('4', 'Junior', '40000');
分析数据
实现
with t1 as (
select employee_id,sum(salary) over(order by salary) total1 from candidates
where experience = 'Senior'
),t2 as (
select max(total1) total from t1 where total1 <= 70000
),t3 as (
select employee_id,sum(salary) over(order by salary) total2 from candidates
where experience = 'Junior'
)
select 'Senior' as experience,count(distinct employee_id) accepted_candidates from t1
where total1 <= 70000
union all
select 'Junior' as experience,count(distinct employee_id) accepted_candidates from t2,t3
where total2 < 70000 - ifnull(total,0)
;