LeetCode 615. Average Salary: Departments VS Company

drop table salary

Create table salary(Id int,employee_id int,amount int,pay_date date);

insert into salary values(1,1,9000,'2017-03-31');
insert into salary values(2,2,6000,'2017-03-31');
insert into salary values(3,3,10000,'2017-03-31');
insert into salary values(4,1,7000,'2017-02-28');
insert into salary values(5,2,6000,'2017-02-28');
insert into salary values(6,3,8000,'2017-02-28');

drop table employee
Create table employee(Id int,department_id int);

insert into employee values(1,1);
insert into employee values(2,2);
insert into employee values(3,2);
 

Given two tables as above, write a query to display the comparison result (higher/lower/same) of the average salary of employees in a department to the company's average salary.

 

So for the sample data above, the result is:

| pay_month | department_id | comparison  |
|-----------|---------------|-------------|
| 2017-03   | 1             | higher      |
| 2017-03   | 2             | lower       |
| 2017-02   | 1             | same        |
| 2017-02   | 2             | same        |
with cte1 as(
select FORMAT(pay_date, 'yyyy-MM') as Pay_Month,avg(amount) as comp_pay from salary
group by FORMAT(pay_date, 'yyyy-MM')
),cte2 as(
select e.department_id,FORMAT(pay_date, 'yyyy-MM') as Pay_Month,AVG(s.amount) as dept_pay from salary s join employee e on s.employee_id=e.Id
group by e.department_id,FORMAT(pay_date, 'yyyy-MM')
) 
select 
cte1.Pay_Month, 
cte2.department_id,
case when cte2.dept_pay > cte1.comp_pay then 'higher'
when cte2.dept_pay < cte1.comp_pay then 'lower'
else 'Same' end as comparison
from cte1 join cte2 on cte1.Pay_Month=cte2.Pay_Month
order by Pay_Month desc,cte2.department_id


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值