Try something like this:DECLARE @NumOfVisits TABLE( CustomerID INT NOT NULL, MonthID INT NOT NULL, MonthDate DATE NOT NULL, NumOfVisits INT NOT NULL, PRIMARY KEY(CustomerID, MonthDate));INSERT INTO @NumOfVisits(CustomerID, MonthID, MonthDate, NumOfVisits) VALUES(001, 200405, '20040501', 1), (001, 200406, '20040601', 2), (001, 200407, '20040701', 1), (001, 200505, '20050501', 5), (001, 200507, '20050701', 10), (002, 200811, '20081101', 3), (002, 200811, '20081120', 1);SELECT T1.CustomerID, T1.MonthID, T2.NumOfVisitsInLast12Month FROM (SELECT T1.CustomerID, T1.MonthID, DATEADD(DAY, -1, DATEADD(MONTH, 1, CAST(CAST(T1.MonthID AS CHAR(6)) + '01' AS DATE))) AS MonthDate FROM @NumOfVisits AS T1 GROUP BY T1.CustomerID, T1.MonthID) AS T1 CROSS APPLY (SELECT SUM(T2.NumOfVisits) AS NumOfVisitsInLast12Month FROM @NumOfVisits AS T2 WHERE T2.CustomerID = T1.CustomerID AND T2.MonthDate <= T1.MonthDate AND T2.MonthDate > DATEADD(MONTH, -13, T1.MonthDate)) AS T2;