Find Cumulative Salary of an Employee

hard database sql

Problem

Employee(id, month, salary). For each employee, compute cumulative salary over the last 3 months excluding the most-recent month.

Inpute=[(1,1,20),(1,2,30),(1,3,40),(1,4,60),(1,7,90)]
Output[(1,4,30+40+60=130),(1,3,20+30+40=90),(1,2,20+30=50),(1,1,20)]
Drop the most recent month (7) and roll a 3-month window over the rest.

SELECT a.id, a.month, SUM(b.salary) AS Salary
FROM Employee a JOIN Employee b
  ON a.id = b.id AND b.month BETWEEN a.month - 2 AND a.month
WHERE (a.id, a.month) NOT IN (SELECT id, MAX(month) FROM Employee GROUP BY id)
GROUP BY a.id, a.month
ORDER BY a.id, a.month DESC;
Time: O(n) Space: O(n)