The following works:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols =
STUFF
(
(
SELECT ',' + QUOTENAME(b."NewName")
FROM (
SELECT myKey,
win = SUM(win)
FROM xxx.dbo.yyy
GROUP BY myKey
) x
INNER JOIN #NameSwitch b ON
x.myKey = b.myKey
ORDER BY x.win DESC
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'');
SET @query =
'SELECT [Measure],' + @cols + '
FROM
(
SELECT [NewName], [Measure], [Amount]
FROM #UnpivottedData x
) x
PIVOT
(
SUM(Amount)
FOR [NewName] in (' + @cols + ')
) p ';
EXECUTE(@query);
But the problem is I'd like to input the results into a temporary table #xxx and then later on be able to use this data via SELECT * FROM #xxx.
Do I need to CREATE #xxx using dynamic sql before running the above? If so can anyone point me in the direction of an example where this is done.