Disclaimer: You should seriously consider representing the SalaryMonth
using a standard SQL Server date or timestamp column. Using string month names creates all sorts of problems, hence my verbose answer below.
My approach is to use a CTE to assign a numerical position to each month name (cte1
). Then, I join this to your original table (cte2
). Finally, we can do a self join of cte2
to compute the rolling salary over the course of the table.
There is probably a way to use the month names to create a date object of some sort, but I couldn't think of it, and in any case doing so would probably require assigning a dummy year, and possibly other things.
WITH cte1 AS (
SELECT 'January' AS SalaryMonth, 1 AS MonthPos
UNION ALL
SELECT 'Februrary', 2
UNION ALL
SELECT 'March', 3
UNION ALL
SELECT 'April', 4
UNION ALL
SELECT 'May', 5
UNION ALL
SELECT 'June', 6
UNION ALL
SELECT 'July', 7
UNION ALL
SELECT 'August', 8
UNION ALL
SELECT 'September', 9
UNION ALL
SELECT 'October', 10
UNION ALL
SELECT 'November', 11
UNION ALL
SELECT 'December', 12
),
WITH cte2 AS (
SELECT t1.EmpID,
t1.SalaryMonth,
t2.MonthPos,
t1.Salary
FROM yourTable t1
INNER JOIN cte1 t2
ON t1.SalaryMonth = t2.SalaryMonth
)
SELECT t1.EmpID,
t1.SalaryMonth,
SUM(t2.Salary) AS Salary
FROM cte2 t1
INNER JOIN cte2 t2
ON t1.MonthPos >= t2.MonthPos
GROUP BY t1.EmpID,
t1.SalaryMonth