LeetCode(数据库)- 平均工资:部门与公司比较
Posted Lux_Sun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode(数据库)- 平均工资:部门与公司比较相关的知识,希望对你有一定的参考价值。
题目链接:点击打开链接
题目大意:略。
解题思路:注意解决方案(2)中 date_format 用法。
AC 代码
-- 解决方案(1)
WITH t1 AS(
SELECT s.*, e.department_id FROM salary s JOIN employee e ON s.employee_id = e.employee_id
),
t2 AS(
SELECT SUBSTRING(pay_date, 1, 7) pay_month, AVG(amount) co_avg FROM t1 GROUP BY pay_month
),
t3 AS(
SELECT SUBSTRING(pay_date, 1, 7) pay_month, department_id, AVG(amount) de_avg FROM t1 GROUP BY pay_month, department_id
)
SELECT t2.pay_month, department_id, CASE
WHEN t2.co_avg = t3.de_avg THEN 'same'
WHEN t2.co_avg > t3.de_avg THEN 'lower'
ELSE 'higher'
END AS comparison
FROM t2 JOIN t3 ON t2.pay_month = t3.pay_month
-- 解决方案(2)
select department_salary.pay_month, department_id,
case
when department_avg>company_avg then 'higher'
when department_avg<company_avg then 'lower'
else 'same'
end as comparison
from
(
select department_id, avg(amount) as department_avg, date_format(pay_date, '%Y-%m') as pay_month
from salary join employee on salary.employee_id = employee.employee_id
group by department_id, pay_month
) as department_salary
join
(
select avg(amount) as company_avg, date_format(pay_date, '%Y-%m') as pay_month from salary group by date_format(pay_date, '%Y-%m')
) as company_salary
on department_salary.pay_month = company_salary.pay_month;
以上是关于LeetCode(数据库)- 平均工资:部门与公司比较的主要内容,如果未能解决你的问题,请参考以下文章
每日SQL打卡DAY 9丨平均工资:部门与公司比较难度困难
查询各个部门中各职位的人数与平均工资? 查询工资,奖金与10号部门某员工工资,奖金都相同的员工? SQL