简介:
详解leetcode 数据库615题
关注两个函数的使用
题目中有两个容易忽视的点:
- 每个部门的平均工资不同
- 每个部门每个月的平均工资不同
解题思路:
1、计算每个月的平均工资,创建一个company_salary的表
select avg(amount) as company_avg,
date_formant(pay_date,'%Y-%m')as pay_month
from salary
group by date_format(pay_date,'%Y-%m')
2、计算每个部门每个月的平均工资,创建一个名为department_salary的表
用了join 函数
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
;
3、用case when 链接 department_salary.pay_month = company _salary.pay_month,两个表连在一起
!注意:select 后面跟的是case,from放在case 完了,ēnd as x x x可以命名这个比较列
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
(#创建一个department——salary 每个月平均工资表:
select department_id, avg(amount) as department_avg, date_format(pay_date, '%Y-%m') as pay_month
from salary
# 和employee表通过employee_id 联系在一起
join employee on salary.employee_id = employee.employee_id
group by department_id, pay_month
) as department_salary
join
(#和创建的名为company_salary的表,通过pay_month 联系在一起
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') #注意这里只group by了月份
) as company_salary
on department_salary.pay_month = company_salary.pay_month
;
这里单独说一下date_format()函数
(图片来自w3school ,仅供学习使用)
对于pay_date ( 2017-03-31)这种形式,若想只要年月表示为(2017-03),也可以用 left(pay_date,7) 表示