I have the following source and destination tables in SQL Server 2008R2. How can I do pivot(s) in TSQL to transform SourceTbl
into DestTbl
? Hoping
Wow this was more complicated than i imagined, but I did get it to work great! thanks. This was my final version. The TextKey contains the data you want to turn into columns, and the TextValue is the value that ends up inside each cell.
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ', ' + QUOTENAME(TextKey)
from #SourceTbl
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT FromEntityID, DisplayName, ' + @cols + '
FROM
(
select FromEntityID, DisplayName, TextKey, TextValue
from #SourceTbl
) x
pivot
(
min(TextValue)
for TextKey in (' + @cols + ')
) p
ORDER BY FromEntityID
'
execute(@query)