Skip to content
Advertisement

Recursive CTE to SUM amount column using date column as terminating condition

I have a table containing loan data including the start date, loan term (how many months the loan will last), and monthly payment.
I am trying to create a recursive CTE that will return the SUM of payments made each month for the past 12 months.

Sample Data:

Here’s what I have tried:

which returns this:

I can tell this is wrong because 2019-08 should have 12202.00 in total_monthly_payments and 2020-08 should have 12194.00 in total_monthly_payments, but I’m not sure where I’m going wrong. It seems either the way I increment the current month in the recursive member or something with the final query is off, but I am currently stuck. Any advice is greatly appreciated!

Advertisement

Answer

I think your query is working fine as you are filtering the latest one year records, so the current month is filtered first (actually the issue is happening because of the day value in current_month, we should use the first date of month to get the correct results) and then aggregation is performed on the resulting set. You can combine the records first and then apply filter later like below:

Also, for 201908, the total would be 12136.0 from the following:

(‘4/3/2016’, 72, 12000), –12000

(‘9/15/2017’, 31, 8), –8

(’10/13/2017′, 52, 128) –128

Please find the db<>fiddle here.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement