SQL 将列转置为行

SQL Transpose Columns into Rows

我一直在尝试转置这个;

**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

我已经研究过如何使用 pivot/unpivot,我已经做到了这一点

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;

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

如有任何帮助或指导,我们将不胜感激。

您可以使用以下查询来获得您想要的结果:

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 link : SQL Fiddle

尝试使用 LISTAGG:

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

More info on LISTAGG