;WITH CTEdata AS (SELECT ExecSeq = ROW_NUMBER() OVER (ORDER BY Dates.[year], Dates.[Month]), r.Acct_no, r.Amount, Dates.[Month], Dates.[year], i.InterestRate, CAST(0 AS float) AS Interest FROM ( SELECT [Year], [month] FROM ( (SELECT TOP 12 [month] = ROW_NUMBER() OVER(ORDER BY [name]) FROM master.sys.columns) m CROSS JOIN (SELECT 2007 AS [Year] UNION ALL SELECT 2008 UNION ALL SELECT 2009 UNION ALL SELECT 2010) y ) WHERE NOT ([Year] = 2010 AND [month] > 2) AND NOT ([Year] = 2007 AND [month] < 8)) DatesLEFT JOIN #Refunds r ON r.[year] = Dates.[year] AND r.[Month] = Dates.[Month]LEFT JOIN #InterestRates i ON i.[year] = Dates.[year] AND i.[Month] = Dates.[Month]),Calculator AS (SELECT ExecSeq, Acct_no, Amount, [Month], [year], InterestRate, Interest FROM CTEdata WHERE ExecSeq = 1 UNION ALLSELECT cr.ExecSeq, ISNULL(cr.Acct_no, lr.Acct_no), ISNULL(cr.Amount, 0), cr.[Month], cr.[year], cr.InterestRate, Interest = (lr.Amount + lr.Interest) * (1 + (cr.InterestRate/12)) FROM Calculator lrINNER JOIN CTEdata cr ON cr.ExecSeq = lr.ExecSeq+1 )SELECT * FROM Calculator ORDER BY ExecSeq