I creating dynamic sql using multiple CTEs and temp tables. One of table looks like folloing:
id datapoint_no load_timestamp practice
----------------- -------------- --------
1 1 2013-12-04 CSS
2 1 2013-12-04 TS
3 1 2013-12-04 MC
4 2 2013-11-25 CSS
5 2 2013-11-25 TS
6 2 2013-11-25 MC
7 3 2013-11-18 CSS
8 3 2013-11-18 TS
9 3 2013-11-18 MC
10 4 NULL CSS
11 4 NULL TS
12 4 NULL MC
13 5 NULL CSS
14 5 NULL TS
15 5 NULL MC
Also I have couple of CTEs which creates script with another cte =) based on table above like:
data_1 AS (
SELECT amount AS TCV,
SUM(amount * probability/100) AS WeightedTCV,
SUM(abr) AS ABR,
SUM(abr * project_margin_c/100) AS ABP,
SUM(NULL) AS ClosedDeals
FROM dbo.opportunities
WHERE load_timestamp='2013-12-04' AND practice_c='CSS'
),
data_2 AS (
SELECT amount AS TCV,
SUM(amount * probability/100) AS WeightedTCV,
SUM(abr) AS ABR,
SUM(abr * project_margin_c/100) AS ABP,
SUM(NULL) AS ClosedDeals
FROM dbo.opportunities
WHERE load_timestamp='2013-12-04' AND practice_c='TS'
),
..... about 15 other data_XXX
Now I want to complete this script with select
and from
and here I've been stopped. I need to union data which belong to same load_timestamp and left join all other data from from other timestamps).
Maybe I am using not the best way of initial script preparation but I do not know how to do it better way.
Finally something like following table should be result of script exection:
practice load_timestamp_1 TCV_1 WeightedTCV_2 ABR_1 ABR_1 load_timestamp_2 TCV_2 WeightedTCV_2 ABR_2 ABR_2
CSS 2013-12-04 xxx yyy zzz www 2013-11-25 xxx yyy zzz www
TS 2013-12-04 xxx yyy zzz www 2013-11-25 xxx yyy zzz www
MC 2013-12-04 xxx yyy zzz www 2013-11-25 xxx yyy zzz www
...................