Average Salary: Departments VS Company

hard database sql

Problem

salary(id, employee_id, amount, pay_date) and employee(id, department_id). Per (pay_month, department), label avg dept salary as higher/lower/same vs company avg that month.

Inputsal=[(1,1,9000,'2017-03-31'),(2,2,6000,'2017-03-31')] emp=[(1,1),(2,2)]
Output[('2017-03',1,'higher'),('2017-03',2,'lower')]
Company avg in March is 7500; dept 1 (9000) is higher, dept 2 (6000) is lower.

SELECT d.pay_month, d.department_id,
  CASE WHEN d.dept_avg > c.comp_avg THEN 'higher'
       WHEN d.dept_avg < c.comp_avg THEN 'lower'
       ELSE 'same' END AS comparison
FROM (
  SELECT DATE_FORMAT(s.pay_date, '%Y-%m') AS pay_month,
         e.department_id, AVG(s.amount) AS dept_avg
  FROM Salary s JOIN Employee e ON s.employee_id = e.employee_id
  GROUP BY pay_month, e.department_id
) d
JOIN (
  SELECT DATE_FORMAT(pay_date, '%Y-%m') AS pay_month, AVG(amount) AS comp_avg
  FROM Salary
  GROUP BY pay_month
) c ON d.pay_month = c.pay_month;
Time: O(n) Space: O(n)