简体   繁体   中英

SQL Transpose Columns into Rows

I've been trying to transpose this;

**ProjectNum    PillarID    BusinessPillar**
95329           29          Pillar29
95329           1           Pillar1
95354           1           Pillar1
95354           4           Pillar4
95354           7           Pillar7

Into this;

**ProjectNum    Pillars**
95329           Pillar1, Pillar29
95354           Pillar1, Pillar4, Pillar7

I have looked at using pivot/unpivot and I've gotten this far

DECLARE @cols AS NVARCHAR(MAX),
    @query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(PillarID) 
                from dbo.MyTable
                group by BusinessPillar, PillarID
                order by PillarID
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')
set @query = N'SELECT ProjectNum, ' + @cols + N' from 
         (
            select ProjectNum, PillarID, BusinessPillar
            from dbo.MyTable
        ) x
        pivot 
        (
            max(BusinessPillar)
            for PillarID in (' + @cols + N')
        ) p '
exec sp_executesql @query;

However I am having a lot of trouble figuring out how to combine all of the pivoted results into a single, comma separated column like in my desired example.

Any help or direction is appreciated.

You can use the following query to get the result that you want:

SELECT ProjectNum, STUFF(
     (SELECT DISTINCT ', ' + BusinessPillar
      FROM Test
      WHERE ProjectNum = t.ProjectNum
      FOR XML PATH (''))
      , 1, 1, '')  AS Pillars
      FROM Test as t
      GROUP BY ProjectNum

Here's the SQL Fiddle link : SQL Fiddle

Try using LISTAGG:

SELECT ProjectNum, LISTAGG(BusinessPillar, ', ') WITHIN GROUP (ORDER BY BusinessPillar) AS PILLARS
      FROM Test
      GROUP BY ProjectNum

More info on LISTAGG

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM