LeetCode(数据库)- 平均工资:部门与公司比较

简介: 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每日练习(三)
数据库LeetCode每日练习(三)
数据库LeetCode每日练习(三)
|
SQL 数据库
数据库LeetCode每日练习(二)
数据库LeetCode每日练习(二)
数据库LeetCode每日练习(二)
|
SQL 数据库
数据库LeetCode每日练习(一)
数据库LeetCode每日练习(一)
数据库LeetCode每日练习(一)
|
数据库
LeetCode(数据库)- Hopper Company Queries II
LeetCode(数据库)- Hopper Company Queries II
100 0
LeetCode(数据库)- Hopper Company Queries II
|
数据库
LeetCode(数据库)- 2142. The Number of Passengers in Each Bus I
LeetCode(数据库)- 2142. The Number of Passengers in Each Bus I
205 0
|
数据库
LeetCode(数据库)- The Number of Seniors and Juniors to Join the Company II
LeetCode(数据库)- The Number of Seniors and Juniors to Join the Company II
119 0
|
数据库
LeetCode(数据库)- Number of Accounts That Did Not Stream
LeetCode(数据库)- Number of Accounts That Did Not Stream
119 0
|
数据库
LeetCode(数据库)- The Airport With the Most Traffic
LeetCode(数据库)- The Airport With the Most Traffic
137 0
|
数据库
LeetCode(数据库)- The Category of Each Member in the Store
LeetCode(数据库)- The Category of Each Member in the Store
123 0
|
数据库
LeetCode(数据库)- 上级经理已离职的公司员工
LeetCode(数据库)- 上级经理已离职的公司员工
134 0