CCP months QUART YEARS GTS
---- ------ ----- ----- ---
CCP1 1 1 2015 5
CCP1 2 1 2015 6
CCP1 3 1 2015
Without a CTE. I'd suggest possible working with the months and years in an actual date format. I might become a bit easier to manage the transition of the Years 2015 vs 2016 becomes a simple DATEADD(MM,-1,dateCol) as opposed to figuring out when to subtract or add a year. I haven't implemented in this solution, but could help if you needed it. It could lead to a pretty effective indexing strategy to speed the query up if you have a large data set. I believer it would also be possible to implement this with LAG as well.
create table #tmp_BASELINE (
CCP char(4),
BASELINE numeric(22,6),
YEARS int ,
QUART int)
create table #tmp_gts (
CCP char(4),
months int,
QUART int,
YEARS int,
GTS numeric(22,6)
)
insert into #tmp_BASELINE
SELECT 'CCP1' AS CCP,10 AS BASELINE, 2015 AS YEARS,1 AS QUART
insert into #tmp_gts
SELECT 'CCP1' AS CCP,1 AS months,1 AS QUART ,2015 AS YEARS, 50 AS GTS UNION
SELECT 'CCP1' AS CCP,2 AS months,1 AS QUART ,2015 AS YEARS, 52 AS GTS UNION
SELECT 'CCP1' AS CCP,3 AS months,1 AS QUART ,2015 AS YEARS, 57 AS GTS UNION
SELECT 'CCP1' AS CCP,4 AS months,2 AS QUART ,2015 AS YEARS, 59 AS GTS UNION
SELECT 'CCP1' AS CCP,5 AS months,2 AS QUART ,2015 AS YEARS, 61 AS GTS UNION
SELECT 'CCP1' AS CCP,6 AS months,2 AS QUART ,2015 AS YEARS, 65 AS GTS UNION
SELECT 'CCP1' AS CCP,7 AS months,3 AS QUART ,2015 AS YEARS, 69 AS GTS UNION
SELECT 'CCP1' AS CCP,8 AS months,3 AS QUART ,2015 AS YEARS, 73 AS GTS UNION
SELECT 'CCP1' AS CCP,9 AS months,3 AS QUART ,2015 AS YEARS, 78 AS GTS UNION
SELECT 'CCP1' AS CCP,10 AS months,4 AS QUART ,2015 AS YEARS, 84 AS GTS UNION
SELECT 'CCP1' AS CCP,11 AS months,4 AS QUART ,2015 AS YEARS, 90 AS GTS UNION
SELECT 'CCP1' AS CCP,12 AS months,4 AS QUART ,2015 AS YEARS, 95 AS GTS
SELECT * FROM #tmp_BASELINE
SELECT CCP,
Months,
QUART,
YEARS,
GTS,
SUM(GTS) OVER (PARTITION BY QUART) as QTRGTS,
COALESCE((SELECT DISTINCT SUM(PGT.GTS) OVER (PARTITION BY QUART) FROM #tmp_gts as PGT WHERE GTS.YEARS = PGT.YEARS AND PGT.QUART = GTS.QUART-1),(SELECT TOP 1 BaseLine FROM #tmp_BASELINE)) as Modifier,
GTS * COALESCE((SELECT DISTINCT SUM(PGT.GTS) OVER (PARTITION BY QUART) FROM #tmp_gts as PGT WHERE GTS.YEARS = PGT.YEARS AND PGT.QUART = GTS.QUART-1),(SELECT TOP 1 BaseLine FROM #tmp_BASELINE)) as GTSxModifier
FROM #tmp_gts as GTS