LeetCode 【困难】数据库-第615:平均工资:部门与公司比较(Case when ‘分类’ )

题目:给如下两个表,写一个查询语句,求出在每一个工资发放日,每个部门的平均工资与公司的平均工资的比较结果 (高 / 低 / 相同)。

1. 不同月份、不同部门的平均工资(group by 两个字段)

select date_format(pay_date,'%Y-%m') as pay_month,department_id,avg(amount) as e_m_d_avg
from salary s left join employee e
on s.employee_id=e.employee_id
group by department_id,pay_month

2. 不同月份、公司的平均工资

select date_format(pay_date,'%Y-%m') as pay_m,avg(amount) as company_avg
from salary
group by pay_m

3.拼接、case when .条件. then .A. when .条件. then .B. else .C. end as 字段名

select pay_month,department_id,
case when e_m_d_avg > company_avg then 'higher' 
                                    when e_m_d_avg < company_avg then 'lower' else 'same' end as comparison
from(
select date_format(pay_date,'%Y-%m') as pay_month,department_id,avg(amount) as e_m_d_avg
from salary s left join employee e
on s.employee_id=e.employee_id
group by department_id,pay_month
) a,

(
select date_format(pay_date,'%Y-%m') as pay_m,avg(amount) as company_avg
from salary
group by pay_m
) b
where pay_month=pay_m 
order by department_id,pay_month;

posted @ 2021-07-02 19:02  hangover  阅读(87)  评论(0编辑  收藏  举报