I have a recursive CTE that calculates projected profit for the duration of a project. I'm trying to figure out to add a corresponding month/date to each iteration/period. My CTE is as follows. No project can exceed 48 months in length, hence my max recursion value of 48. So if a project started on January 2, 2017, and is 37 months in duration, I'd like to associate a month for each period.
DECLARE @OrigAmt MONEY
DECLARE @Duration INT
SET @OrigAmt = 49673330
SET @Duration = 37;
WITH CTE AS (
SELECT [Duration], [Remaining Periods],
Amt = CAST([Forecast Rate] * @OrigAmt AS MONEY),
Balance = CAST(@OrigAmt - (@OrigAmt * [Forecast Rate]) AS MONEY)
FROM DataWarehouse.dbo.dimForecast_Rates
WHERE [Duration] = @Duration AND [Remaining Periods] = 1
UNION ALL
SELECT b.Duration, b.[Remaining Periods],
Amt = CAST(b.[Forecast Rate] * CTE.Balance AS MONEY),
Balance = CAST(CTE.Balance - (CTE.Balance * b.[Forecast Rate]) AS MONEY)
FROM CTE
JOIN DataWarehouse.dbo.dimForecast_Rates b ON b.Duration = CTE.Duration AND b.[Remaining Periods] = CTE.[Remaining Periods] + 1
)
SELECT Duration,
[Remaining Periods],
Amt ,
Balance
FROM CTE
ORDER BY [Remaining Periods]
OPTION (MAXRECURSION 48)
↧