SQLServer 行转列 - 使用PIVOT对结果集进行数据透视

使用PIVOT对结果集进行数据透视
SELECT FROM Table PIVOT(任意聚合函数(聚合字段) FOR 待扩展字段名 IN (待扩展元素集)) AS T
其中【待扩展元素集】一定一串静态元素集,即必须具体列出需要透视的字段

DECLARE @cmd NVARCHAR(MAX);
DECLARE @names NVARCHAR(MAX);

SET @names = STUFF(( SELECT ',' + Name
                     FROM   dbo.ProposedProjectSettings
                     WHERE  ProposedProjectID = '100012'
                   FOR
                     XML PATH('')
                   ), 1, 1, '');
SET @cmd = '
SELECT  *
FROM    ( SELECT    Name ,
                    Value
          FROM      dbo.ProposedProjectSettings
          WHERE     ProposedProjectID = ''100012''
        ) p PIVOT( MIN(Value) FOR Name IN ( '+@names+' ) )
AS pvt;';

EXEC(@cmd)

转置前

转置后

posted @ 2021-08-18 11:41  xuxuzhaozhao  阅读(142)  评论(0编辑  收藏  举报