Pivot multiple columns based on one column in SQL Server

后端 未结 2 1980
说谎
说谎 2020-11-30 06:14

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

2条回答
  •  执笔经年
    2020-11-30 06:30

    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)
    

提交回复
热议问题