I would like to create below pivot data in a more dynamic way based on what is in the TMP table without hard coding it. Is there any way to do that?
The structure has to be flexible since it can change frequently.
Means I would like to create columns based on what is in the AGG field in the TMP table. Currently the table has three values --> 'XX', 'YY' and 'ZZ' hence I need to create three columns. But in the above SQL I hard coded the three columns. This has to be changed to a more dynamic implementation since the TMP table can also have more values. Hence I would need to create corresponding columns. I hope this is somehow understandable.
WITH TMP AS
(SELECT 'XX' AS AGG,
50 AS VALUE,
0 AS MONTH
UNION ALL
SELECT 'XX' AS AGG,
150 AS VALUE,
1 AS MONTH
UNION ALL
SELECT 'XX' AS AGG,
300 AS VALUE,
2 AS MONTH
UNION ALL
SELECT 'YY' AS AGG,
25 AS VALUE,
0 AS MONTH
UNION ALL
SELECT 'YY' AS AGG,
50 AS VALUE,
1 AS MONTH
UNION ALL
SELECT 'YY' AS AGG,
75 AS VALUE,
2 AS MONTH
UNION ALL
SELECT 'ZZ' AS AGG,
500 AS VALUE,
0 AS MONTH
UNION ALL
SELECT 'ZZ' AS AGG,
600 AS VALUE,
1 AS MONTH
UNION ALL
SELECT 'ZZ' AS AGG,
700 AS VALUE,
2 AS MONTH),
SELECT Month,
MAX(CASE Agg WHEN 'XX' THEN VALUE END) AS XX,
MAX(CASE Agg WHEN 'YY' THEN VALUE END) AS YY,
MAX(CASE Agg WHEN 'ZZ' THEN VALUE END) AS ZZ
FROM TMP
GROUP BY MONTH