SQL架构
表: Candidates
+-------------+------+ | Column Name | Type | +-------------+------+ | employee_id | int | | experience | enum | | salary | int | +-------------+------+ employee_id是此表的主键列。 经验是包含一个值(“高级”、“初级”)的枚举类型。 此表的每一行都显示候选人的id、月薪和经验。
一家公司想雇佣新员工。公司的工资预算是 70000
美元。公司的招聘标准是:
- 雇佣最多的高级员工。
- 在雇佣最多的高级员工后,使用剩余预算雇佣最多的初级员工。
编写一个SQL查询,查找根据上述标准雇佣的高级员工和初级员工的数量。
按 任意顺序 返回结果表。
查询结果格式如下例所示。
示例 1:
输入: Candidates table: +-------------+------------+--------+ | employee_id | experience | salary | +-------------+------------+--------+ | 1 | Junior | 10000 | | 9 | Junior | 10000 | | 2 | Senior | 20000 | | 11 | Senior | 20000 | | 13 | Senior | 50000 | | 4 | Junior | 40000 | +-------------+------------+--------+ 输出: +------------+---------------------+ | experience | accepted_candidates | +------------+---------------------+ | Senior | 2 | | Junior | 2 | +------------+---------------------+ 说明: 我们可以雇佣2名ID为(2,11)的高级员工。由于预算是7万美元,他们的工资总额是4万美元,我们还有3万美元,但他们不足以雇佣ID为13的高级员工。 我们可以雇佣2名ID为(1,9)的初级员工。由于剩下的预算是3万美元,他们的工资总额是2万美元,我们还有1万美元,但他们不足以雇佣ID为4的初级员工。
示例 2:
输入: Candidates table: +-------------+------------+--------+ | employee_id | experience | salary | +-------------+------------+--------+ | 1 | Junior | 10000 | | 9 | Junior | 10000 | | 2 | Senior | 80000 | | 11 | Senior | 80000 | | 13 | Senior | 80000 | | 4 | Junior | 40000 | +-------------+------------+--------+ 输出: +------------+---------------------+ | experience | accepted_candidates | +------------+---------------------+ | Senior | 0 | | Junior | 3 | +------------+---------------------+ 解释: 我们不能用目前的预算雇佣任何高级员工,因为我们需要至少80000美元来雇佣一名高级员工。 我们可以用剩下的预算雇佣三名初级员工。
with t1 as (select
employee_id,experience,salary,sum(salary) over(partition by experience order by salary rows between unbounded preceding and current row) so
#按 experience 分组开窗,按salary 生序排列逐一求和 然后 <=70000 就是能招聘的 员工
from
Candidates
),
t2 as (
select
"Senior" experience,count(employee_id) accepted_candidates,70000-ifnull(max(so),0) m # 能招聘的 Senior 等级员工
from
t1
where
experience = "Senior" and so<=70000
)
select
experience,accepted_candidates
from
t2
union all #上下两表拼接 就是题中需求
select
"Junior" experience,count(employee_id) accepted_candidates # 能招聘的 Junior 等级员工
from
t1
where
experience = "Junior" and so<=(select m from t2)
笔记:
注意:
select
"Junior" experience,count(employee_id) accepted_candidates # 能招聘的 Junior 等级员工
from
t1
where
experience = "Junior" and so<=(select m from t2)
第一列 固定 输出 "Junior" 为了保证 where 条件筛选不出任何内容时 也能 正常输出内容
"Junior" 0 ( count(null) =>0 )