SQL将列转置为行

时间:2018-08-28 17:27:50

标签: sql sql-server tsql pivot unpivot

我一直在尝试换位;

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

对此;

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

我已经看过使用数据透视/不旋转透视,到此为止

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;

但是,像我想要的示例一样,我在弄清楚如何将所有透视结果合并到一个用逗号分隔的单个列中时遇到很多麻烦。

感谢任何帮助或指导。

2 个答案:

答案 0 :(得分:0)

您可以使用以下查询来获得所需的结果:

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

这是SQL Fiddle链接: SQL Fiddle

答案 1 :(得分:0)

尝试使用LISTAGG:

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

More info on LISTAGG