Sqlserver
 sql >> Datenbank >  >> RDS >> Sqlserver

Dynamische Pivot-Tabelle mit mehreren Spalten in SQL Server

Bitte verwenden Sie dies (wenn Sie ein Sortierungsproblem erhalten, ändern Sie bitte alle 3 INT-Datentypen):

STATISCHER Code:

SELECT HEADER, [A_1],[B_2],[C_3],[D_4],[E_5],[F_6]        
FROM    
(SELECT DECK,HEADER, VALUE FROM REPORT   
    UNPIVOT      
    ( 
    VALUE FOR HEADER IN ([JIB_IN],[REV],[REV_INSIGHT],[JIB_OUT],[CREATION])  
    ) UNPIV
) SRC     
PIVOT    
(
    SUM(VALUE) 
    FOR DECK IN ([A_1],[B_2],[C_3],[D_4],[E_5],[F_6]) 
) PIV

Dynamisches SQL verwenden:

DECLARE @COLSUNPIVOT AS NVARCHAR(MAX),
@QUERY  AS NVARCHAR(MAX),
@COLSPIVOT AS  NVARCHAR(MAX)

SELECT @COLSUNPIVOT = STUFF((SELECT ','+QUOTENAME(C.NAME)
FROM SYS.COLUMNS AS C
WHERE C.OBJECT_ID = OBJECT_ID('REPORT') AND C.NAME <> 'DECK'
FOR XML PATH('')), 1, 1, '')

SELECT @COLSPIVOT = STUFF((SELECT  ',' + QUOTENAME(DECK)
FROM REPORT T FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') ,1,1,'')

SET @QUERY 
= 'SELECT HEADER, '[email protected]+'
FROM
(
SELECT DECK,HEADER,VALUE FROM REPORT
UNPIVOT
(
  VALUE FOR HEADER IN ('[email protected]+')
) UNPIV
) SRC
PIVOT
(
SUM(VALUE)
FOR DECK IN ('[email protected]+')
) PIV'

EXEC(@QUERY)