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

Server SQL Pivot Multi Kolom

Jika nilai ABC dan XYG diketahui dimuka Anda dapat melakukan agregasi bersyarat

SELECT ID,
       MAX(CASE WHEN type = 'ABC' THEN 'ABC' END) Type1,
       MAX(CASE WHEN type = 'ABC' THEN Date END) Date1,
       MAX(CASE WHEN type = 'XYG' THEN 'XYZ' END) Type2,
       MAX(CASE WHEN type = 'XYG' THEN Date END) Date2,
       MAX(Location) Location,
       MAX(Result) Result,
       MAX(CASE WHEN type = 'ABC' THEN [Proc] END) Proc1,
       MAX(CASE WHEN type = 'ABC' THEN ProcDate END) ProcDate1,
       MAX(CASE WHEN type = 'ABC' THEN ProcDetail END) ProcDetail1,
       MAX(CASE WHEN type = 'ABC' THEN ProcNotes END) ProcNotes1,
       MAX(CASE WHEN type = 'XYG' THEN [Proc] END) Proc2,
       MAX(CASE WHEN type = 'XYG' THEN ProcDate END) ProcDate2,
       MAX(CASE WHEN type = 'XYG' THEN ProcDetail END) ProcDetail2,
       MAX(CASE WHEN type = 'XYG' THEN ProcNotes END) ProcNotes2
  FROM
(
  SELECT * FROM table1 -- that's to emulate your current query with multiple joins
) q
 GROUP BY ID

Contoh keluaran:

| ID | TYPE1 |                          DATE1 | TYPE2 |                          DATE2 | LOCATION | RESULT |  PROC1 |                      PROCDATE1 |     PROCDETAIL1 |   PROCNOTES1 |  PROC2 |                      PROCDATE2 |     PROCDETAIL2 |   PROCNOTES2 |
|----|-------|--------------------------------|-------|--------------------------------|----------|--------|--------|--------------------------------|-----------------|--------------|--------|--------------------------------|-----------------|--------------|
|  1 |   ABC | January, 01 2010 00:00:00+0000 |   XYZ | January, 02 2011 00:00:00+0000 |       OK |     AO | Proc_B | January, 01 2013 00:00:00+0000 | This is Details | Proc_B Notes | Proc_B | January, 01 2013 00:00:00+0000 | This is Details | Proc_B Notes |

Ini SQLFiddle demo




  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Cara Mengembalikan Kunci Duplikat dari Dokumen JSON di SQL Server

  2. Sql server 2008 - fitur penyetelan kinerja untuk memasukkan data dalam jumlah besar

  3. Apa perbedaan antara; dan GO di T-SQL?

  4. SQL 2008:Matikan Stop Words untuk Permintaan Pencarian Teks Lengkap

  5. Mengoptimalkan TempDB:Menghindari Kemacetan dan Masalah Kinerja