SQL练习00010

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

表: salary

idemployee_idamountpay_date
1190002017-03-31
2260002017-03-31
33100002017-03-31
4170002017-02-28
5260002017-02-28
6380002017-02-28

employee_id 字段是表 employee 中 employee_id 字段的外键。

employee_iddepartment_id
11
22
32

对于如上样例数据,结果为:

pay_monthdepartment_idcomparison
2017-031higher
2017-032lower
2017-021same
2017-022same
--建表语句
Create table If Not Exists salary (id int, employee_id int, amount int, pay_date date)
Create table If Not Exists employee (employee_id int, department_id int)
Truncate table salary
insert into salary (id, employee_id, amount, pay_date) values ('1', '1', '9000', '2017/03/31')
insert into salary (id, employee_id, amount, pay_date) values ('2', '2', '6000', '2017/03/31')
insert into salary (id, employee_id, amount, pay_date) values ('3', '3', '10000', '2017/03/31')
insert into salary (id, employee_id, amount, pay_date) values ('4', '1', '7000', '2017/02/28')
insert into salary (id, employee_id, amount, pay_date) values ('5', '2', '6000', '2017/02/28')
insert into salary (id, employee_id, amount, pay_date) values ('6', '3', '8000', '2017/02/28')
Truncate table employee
insert into employee (employee_id, department_id) values ('1', '1')
insert into employee (employee_id, department_id) values ('2', '2')
insert into employee (employee_id, department_id) values ('3', '2')



--答案
select
  pay_month,
  department_id,
  case
    when avg_d>avg_p then 'higher'
    when avg_d<avg_p then 'lower'
    else 'same'
  end as comparison
from
  (select
    substr(pay_date,1,7) as pay_month,
    department_id,
    avg(amount) over(partition by pay_date) as avg_p,
    avg(amount) over(partition by pay_date,department_id) as avg_d
  from
    salary s join
    employee e on 
    s.employee_id=e.employee_id
  ) 
  a group by 
  pay_month,department_id order by 
  pay_month desc,department_id
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值