Mysql :date_format、case..when函数

简介:
详解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) 表示

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值