Employee table with itself (as E2) on id and month - 1 to get the salary of the previous month.Employee table with itself again (as E3) on id and month - 2 to get the salary of the month before the previous month.IFNULL to handle cases where there is no salary for the previous months by treating them as 0.LEFT JOIN to join the subquery with the cumulative salary result and filter out the most recent month's salary for each employee.id in ascending order and by month in descending order.erDiagram
Employee {
int id
int month
int salary
}