简体   繁体   中英

Dynamic Column Names with Pivot SQL

Hello all I'm still relatively new to SQL and a search online haven't provided me a solution yet (or its been right in front of me but out of my sphere of knowledge :/). So hoping to try my luck here thanks!

Table:   Servers
Columns: ServerUrl               ServerName
Rows:    //server0001/space0/    Telescope1
         //server0001/space1/    Space
         //server0001/space2/    Planet

Table:   Projects
Columns: ServerUrl               Name          Entity     Type
Rows:    //server0001/space0/    Field1        E          T1
         //server0001/space1/    Field2        T          T1
         //server0001/space2/    Field3        E          T3

With the stored procedure below I was able to return the data as:

So the ServerUrl gets used as the column names as seen below but I want it to be the ServerName instead. I know its possible to set the columns to be ServerNames but how would I go about doing it dynamically since the ServerUrl may change.

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

***Stored Procedure below used to get Results Above

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

Thank you :)

Your stored procedure looks like it's incomplete or you've changed certain things, but I believe you're looking for something like the following:

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;

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