Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

Tabel pivot dinamis dengan banyak kolom di server sql

Silakan gunakan ini (Jika Anda mendapatkan masalah Collation, harap ubah semua 3 tipe data INT):

Kode STATIS:

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

Menggunakan SQL Dinamis:

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)



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Bagaimana membandingkan nilai Null dari kolom database

  2. Jalankan ekspresi matematika dan atur nilainya ke variabel dalam SQL

  3. Membatasi Sesi Pengguna Serentak untuk Login Tertentu di SQL Server

  4. Kinerja Sisipan-Pilih Server Tertaut

  5. SQL Server mengembalikan kesalahan Login gagal untuk pengguna 'NT AUTHORITY\ANONYMOUS LOGON'. di aplikasi Windows