If your ratios are non null, and always greater than -1 (since you need to add 1 anyway to get the multiplication factor) and you are also using SQL Server 2012 or later then your query can be solved without recursion:
WITH Revenue (Revenue) AS (SELECT 100),
Ratios AS (SELECT * FROM (VALUES (1, 0.1), (2, 0.3), (3, 0.2)) t (Month_n, Ratio))
SELECT ra.month_n,
ra.Ratio,
CompoundRatio = EXP(SUM(LOG((1 + ra.Ratio))) OVER(ORDER BY Month_n)),
Result = rv.Revenue * EXP(SUM(LOG((1 + ra.Ratio))) OVER(ORDER BY Month_n))
FROM Ratios AS ra
CROSS JOIN Revenue AS rv;
Which gives:
month_n Ratio Compound Result
-------------------------------------
1 0.1 1.1 110
2 0.3 1.43 143
3 0.2 1.716 171.6
You can use windowed functions to sum up the previous ratios, to get a compound ratio, although since SQL Server does not have a product aggregate you need to use LOG
and EXP
to get the product of the previous ratios.
If your ratios can be negative and/or 0 then you can still do this, but your logic gets a bit more complicated. See this answer for more of an explanation of what the checks are doing:
WITH Revenue (Revenue) AS (SELECT 100),
Ratios AS (SELECT * FROM (VALUES (1, 0.1), (2, 0.3), (3, 0.2), (4, -0.1), (5, 0.2), (6, -0.2), (7, 0.05), (8, -1.1)) t (Month_n, Ratio))
SELECT ra.month_n,
ra.Ratio,
CompoundRatio = CASE WHEN MIN(ABS(ra.Ratio + 1)) OVER(ORDER BY ra.Month_n) = 0 THEN 0
ELSE CASE WHEN SUM(CASE WHEN ra.Ratio < -1 THEN 1 ELSE 0 END)
OVER(ORDER BY ra.Month_n) % 2 = 1 THEN -1 ELSE 1 END *
EXP(SUM(LOG(ABS(NULLIF(1 + ra.Ratio, 0)))) OVER(ORDER BY Month_n))
END,
Result = CASE WHEN MIN(ABS(ra.Ratio + 1)) OVER(ORDER BY ra.Month_n) = 0 THEN 0
ELSE CASE WHEN SUM(CASE WHEN ra.Ratio < -1 THEN 1 ELSE 0 END)
OVER(ORDER BY ra.Month_n) % 2 = 1 THEN -1 ELSE 1 END *
EXP(SUM(LOG(ABS(NULLIF(1 + ra.Ratio, 0)))) OVER(ORDER BY Month_n))
END * rv.Revenue
FROM Ratios AS ra
CROSS JOIN Revenue AS rv;
Results (With sanity check):
month_n Ratio CompoundRatio SQLResult Equation
------------------------------------------------------------------------
1 0.1 1.1 110 100 + 100 x 0.1 = 110
2 0.3 1.43 143 110 + 110 x 0.3 = 143
3 0.2 1.716 171.6 143 + 143 x 0.2 = 171.6
4 -0.1 1.5444 154.44 171.6 + 171.6 x -0.1 = 154.44
5 0.2 1.85328 185.328 154.44 + 154.44 x 0.2 = 185.328
6 -0.2 1.482624 148.2624 185.328 + 185.328 x -0.2 = 148.2624
7 0.05 1.5567552 155.67552 148.2624 + 148.2624 x 0.05 = 155.67552
8 -1.1 -0.15567552 -15.567552 155.67552 + 155.67552 x -1.1 = -15.567552