sql >> Database >  >> RDS >> Sqlserver

Multi Column Pivot SQL Server

Als waarden ABC en XYG zijn vooraf bekend, u kunt voorwaardelijke aggregatie doen

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

Voorbeelduitvoer:

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

Hier is SQLFiddle demo




  1. Meerdere tabellen join MySQL meerdere externe sleutels

  2. Bewerk geselecteerde rijen handmatig in SQL Server

  3. Wanneer CSV-opslagengine gebruiken voor MySQL?

  4. PostgreSQL GROUP_CONCAT() Equivalent