You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
-- 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
0 commit comments