CCP months QUART YEARS GTS
---- ------ ----- ----- ---
CCP1 1 1 2015 5
CCP1 2 1 2015 6
CCP1 3 1 2015
Another alternative is using stacked/cascaded CTEs:
;WITH CteFirstQtr AS(
SELECT g.*,
result = b.BASELINE * g.GTS
FROM gts g
INNER JOIN BASELINE b
ON b.CCP = g.CCP
AND b.YEARS = g.YEARS
AND b.QUART = g.QUART
),
CteSecondQtr AS(
SELECT g.*,
result = t.result * g.gts
FROM gts g
CROSS APPLY(
SELECT SUM(result)
FROM CteFirstQtr
WHERE
CCP = g.CCP
AND Years = g.Years
AND QUART = 1
)t(result)
WHERE g.QUART = 2
),
CteThirdQtr AS(
SELECT g.*,
result = t.result * g.gts
FROM gts g
CROSS APPLY(
SELECT SUM(result)
FROM CteSecondQtr
WHERE
CCP = g.CCP
AND Years = g.Years
AND QUART = 2
)t(result)
WHERE g.QUART = 3
),
CteFourthQtr AS(
SELECT g.*,
result = t.result * g.gts
FROM gts g
CROSS APPLY(
SELECT SUM(result)
FROM CteThirdQtr
WHERE
CCP = g.CCP
AND Years = g.Years
AND QUART = 3
)t(result)
WHERE g.QUART = 4
)
SELECT * FROM CteFirstQtr UNION ALL
SELECT * FROM CteSecondQtr UNION ALL
SELECT * FROM CteThirdQtr UNION ALL
SELECT * FROM CteFourthQtr