CCP months QUART YEARS GTS
---- ------ ----- ----- ---
CCP1 1 1 2015 5
CCP1 2 1 2015 6
CCP1 3 1 2015
Im not sure if the question is how do the over()
logic or perform a recursive cte in 2012 or just calculate in 2012 without recursive cte.
Looks like you were trying to create the PRODUCT()
agreggation equivalent. But as I put in my comment
The function 'Exp' is not a valid windowing function, and cannot be used with the OVER clause.
So I did my version without recursive cte for my answer. I include one aditional year on the sample data with different baseline
gts
for each Quart
Quart
Quart
doing the dummy PRODUCT()
aggregatedSQL Fiddle Demo
WITH gtsTotal as (
SELECT [CCP], [Year], [QUART], SUM([GTS]) as sumGts
FROM gts
GROUP BY [CCP], [Year], [QUART]
),
newBase as (
SELECT g.[CCP], g.[YEAR], b.[BASELINE], 1 as sQuart, b.[BASELINE] as [TotalBase]
FROM gtsTotal g
INNER JOIN baseline b
on g.[Year] = b.[YEARS]
and g.[CCP] = b.[CCP]
WHERE g.[QUART] <= 1
UNION ALL
SELECT g.[CCP], g.[YEAR], b.[BASELINE], MAX(g.[QUART]) + 1 as sQuart, (Exp(Sum(Log(sumGts))) * b.[BASELINE]) as [TotalBase]
FROM gtsTotal g
INNER JOIN baseline b
on g.[Year] = b.[YEARS]
and g.[CCP] = b.[CCP]
WHERE g.[QUART] <= 1
GROUP BY g.[CCP], g.[YEAR], b.[BASELINE]
UNION ALL
SELECT g.[CCP], g.[YEAR], b.[BASELINE], MAX(g.[QUART]) + 1 as sQuart, (Exp(Sum(Log(sumGts))) * b.[BASELINE]) as [TotalBase]
FROM gtsTotal g
INNER JOIN baseline b
on g.[Year] = b.[YEARS]
and g.[CCP] = b.[CCP]
WHERE g.[QUART] <= 2
GROUP BY g.[CCP], g.[YEAR], b.[BASELINE]
UNION ALL
SELECT g.[CCP], g.[YEAR], b.[BASELINE], MAX(g.[QUART]) + 1 as sQuart, (Exp(Sum(Log(sumGts))) * b.[BASELINE]) as [TotalBase]
FROM gtsTotal g
INNER JOIN baseline b
on g.[Year] = b.[YEARS]
and g.[CCP] = b.[CCP]
WHERE g.[QUART] <= 3
GROUP BY g.[CCP], g.[YEAR], b.[BASELINE]
)
SELECT g.CCP, g.months, g.QUART, g.Year, CEILING(g.GTS * n.TotalBase)
FROM newBase n
INNER JOIN gts g
ON n.CCP = g.CCP
AND n.[Year] = g.[Year]
AND n.[sQuart] = g.[QUART]
order by g.[Year], n.sQuart
Output
| CCP | months | QUART | Year | Result|
|------|--------|-------|------|-------|
| CCP1 | 1 | 1 | 2015 | 25 |
| CCP1 | 2 | 1 | 2015 | 30 |
| CCP1 | 3 | 1 | 2015 | 35 |
| CCP1 | 4 | 2 | 2015 | 360 |
| CCP1 | 5 | 2 | 2015 | 180 |
| CCP1 | 6 | 2 | 2015 | 180 |
| CCP1 | 7 | 3 | 2015 | 2160 |
| CCP1 | 8 | 3 | 2015 | 1440 |
| CCP1 | 9 | 3 | 2015 | 720 |
| CCP1 | 10 | 4 | 2015 | 8640 |
| CCP1 | 11 | 4 | 2015 | 12960 |
| CCP1 | 12 | 4 | 2015 | 17280 |