带有数据透视表SQL的动态列名称

时间:2017-06-07 00:44:58

标签: sql sql-server tsql

大家好,我仍然相对较新的SQL和搜索在线天堂还没有为我提供解决方案(或者它在我面前,但在我的知识领域之外:/)。所以希望在这里试试我的运气谢谢!

--- Returned Data Begin ---
Stored Procedure Results:
Columns: Name    Entity  //server0001/space0/   ...space1  ...space2
Rows:    Field1  E       T1                     NULL       NULL
         Field2  T       NULL                   T2         NULL
         Field3  E       NULL                   NULL       T3     

--- Returned Data End ---

使用下面的存储过程,我能够将数据返回为:

所以ServerUrl被用作列名,如下所示,但我希望它是ServerName。我知道可以将列设置为ServerNames但是我将如何动态地执行它,因为ServerUrl可能会更改。

--- STORED PROCEDURE BEGIN ---
DECLARE @Projects varchar(max)
SELECT @ProgramList = COALESCE(@Projects + '], [', '') + ServerURL FROM
Servers ORDER BY ServerURL

SET @ProgramList = CONCAT ('[', @ProgramList + ']')

DECLARE @sql nvarchar(max)
SET @sql = 'select * from ( select P.Name, P.Entity, P.Field, P.ServerUrl 
FROM ProjectFields as P ) as P pivot (min(P.Field) for P.ServerUrl in (' + 
@Projects + ')) as PIV ORDER BY Name'

EXEC sp_executesql @sql1
--- STORED PROCEDURE END ---

***以下存储过程用于获取上面的结果

{{1}}

谢谢:)

1 个答案:

答案 0 :(得分:0)

您的存储过程看起来不完整或者您已经更改了某些内容,但我相信您正在寻找以下内容:

DECLARE @ProgramList VARCHAR(MAX);
SELECT @ProgramList = STUFF((SELECT ',' + QUOTENAME(ServerName) FROM [Servers] ORDER BY ServerURL FOR XML PATH ('')), 1, 1, '');

DECLARE @sql VARCHAR(MAX);
SELECT @sql = '
SELECT *
FROM
(
    SELECT P.Name,
           P.Entity,
           P.Field,
           S.ServerName
    FROM ProjectFields AS P
    JOIN [Servers] AS S
        ON S.ServerURL = P.ServerURL
) AS P
PIVOT
(
    MIN(Field) FOR ServerName IN (' + @ProgramList + ')
) AS PIV
ORDER BY PIV.Name;';

--PRINT @sql;
EXEC sp_executesql @sql;