Hi Nathan
Thanks for posting the sample data and expected results, it doesn't half make a difference. Top work.
Here you go.
;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)
) Dates
LEFT 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 ALL
SELECT 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 lr
INNER JOIN CTEdata cr ON cr.ExecSeq = lr.ExecSeq+1
)
SELECT * FROM Calculator ORDER BY ExecSeq
For better assistance in answering your questions, please read this[/url].
Hidden RBAR: Triangular Joins[/url] / The "Numbers" or "Tally" Table: What it is and how it replaces a loop[/url] Jeff Moden[/url]