Skip to content

Commit a960061

Browse files
authored
Add files via upload
1 parent d42876f commit a960061

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

Hard/Average Salary.sql

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
-- Question 108
2+
-- Given two tables as below, 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.
3+
4+
5+
-- Table: salary
6+
-- | id | employee_id | amount | pay_date |
7+
-- |----|-------------|--------|------------|
8+
-- | 1 | 1 | 9000 | 2017-03-31 |
9+
-- | 2 | 2 | 6000 | 2017-03-31 |
10+
-- | 3 | 3 | 10000 | 2017-03-31 |
11+
-- | 4 | 1 | 7000 | 2017-02-28 |
12+
-- | 5 | 2 | 6000 | 2017-02-28 |
13+
-- | 6 | 3 | 8000 | 2017-02-28 |
14+
15+
16+
-- The employee_id column refers to the employee_id in the following table employee.
17+
18+
19+
-- | employee_id | department_id |
20+
-- |-------------|---------------|
21+
-- | 1 | 1 |
22+
-- | 2 | 2 |
23+
-- | 3 | 2 |
24+
25+
26+
-- So for the sample data above, the result is:
27+
28+
29+
-- | pay_month | department_id | comparison |
30+
-- |-----------|---------------|-------------|
31+
-- | 2017-03 | 1 | higher |
32+
-- | 2017-03 | 2 | lower |
33+
-- | 2017-02 | 1 | same |
34+
-- | 2017-02 | 2 | same |
35+
36+
37+
-- Explanation
38+
39+
40+
-- In March, the company's average salary is (9000+6000+10000)/3 = 8333.33...
41+
42+
43+
-- The average salary for department '1' is 9000, which is the salary of employee_id '1' since there is only one employee in this department. So the comparison result is 'higher' since 9000 > 8333.33 obviously.
44+
45+
46+
-- The average salary of department '2' is (6000 + 10000)/2 = 8000, which is the average of employee_id '2' and '3'. So the comparison result is 'lower' since 8000 < 8333.33.
47+
48+
49+
-- With he same formula for the average salary comparison in February, the result is 'same' since both the department '1' and '2' have the same average salary with the company, which is 7000.
50+
51+
-- Solution
52+
with t1 as(
53+
select date_format(pay_date,'%Y-%m') as pay_month, department_id, avg(amount) over(partition by month(pay_date),department_id) as dept_avg,
54+
avg(amount) over(partition by month(pay_date)) as comp_avg
55+
from salary s join employee e
56+
using (employee_id))
57+
58+
select distinct pay_month, department_id,
59+
case when dept_avg>comp_avg then "higher"
60+
when dept_avg = comp_avg then "same"
61+
else "lower"
62+
end as comparison
63+
from t1
64+
order by 1 desc

0 commit comments

Comments
 (0)