GTS Table
CCP months QUART YEARS GTS
---- ------ ----- ----- ---
CCP1 1 1 2015 5
CCP1 2 1 2015 6
CCP1 3 1 2015 7
CCP1 4 2 2015 4
CCP1 5 2 2015 2
CCP1 6 2 2015 2
CCP1 7 3 2015 3
CCP1 8 3 2015 2
CCP1 9 3 2015 1
CCP1 10 4 2015 2
CCP1 11 4 2015 3
CCP1 12 4 2015 4
Baseline table
CCP BASELINE YEARS QUART
---- -------- ----- -----
CCP1 5 2015 1
Expected result
CCP months QUART YEARS GTS result
---- ------ ----- ----- --- ------
CCP1 1 1 2015 5 25 -- 5 * 5 (here 5 is the baseline)
CCP1 2 1 2015 6 30 -- 6 * 5 (here 5 is the baseline)
CCP1 3 1 2015 7 35 -- 7 * 5 (here 5 is the baseline)
CCP1 4 2 2015 4 360 -- 90 * 4(25+30+35 = 90 is the basline)
CCP1 5 2 2015 2 180 -- 90 * 2(25+30+35 = 90 is the basline)
CCP1 6 2 2015 2 180 -- 90 * 2(25+30+35 = 90 is the basline)
...
next quarter baseline will be (720)
Explantion
Baseline table has single baseline value for each CCP.
The baseline value should be applied to first quarter of each CCP and for the next quarters previous quarter sum value will be the basleine.
Yes i can do this using While Loop or cursor but am looking for a better way of doing it So far i have tried something like this. But didnt wotk out what am i missing here.
Query
;WITH RECURSIVE_CTE
AS (SELECT B.CCP,
G.months,
g.years,
g.quart,
Cast(( B.BASELINE + GTS ) AS NUMERIC(38, 15))AS BASE,
Sum(Cast(( B.BASELINE + GTS ) AS NUMERIC(38, 15)))OVER(PARTITION BY b.CCP) AS Q_SUM
FROM BASELINE B
INNER JOIN GTS G
ON B.CCP = G.CCP
AND b.QUART = g.QUART
AND b.YEARS = g.YEARS
UNION ALL
SELECT G.CCP,
G.months,
g.years,
g.quart,
Cast(( Q_SUM + GTS ) AS NUMERIC(38, 15)),
Sum(Cast(( Q_SUM + GTS ) AS NUMERIC(38, 15)))OVER(PARTITION BY g.CCP, g.years, g.quart) AS Q_SUM
FROM RECURSIVE_CTE C
INNER JOIN GTS G
ON C.CCP = G.CCP
AND G.YEARS = C.YEARS and g.QUART = c.quart + 1)
SELECT *
FROM RECURSIVE_CTE
Note : Am looking for a suggestion in Sql Server 2008