sql >> Databáze >  >> RDS >> Sqlserver

SQL Server s více sloupci Pivot

Pokud hodnoty ABC a XYG jsou předem známé, můžete provést podmíněnou agregaci

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

Ukázkový výstup:

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

Zde je SQLFiddle demo




  1. Funkce ASCIISTR() v Oracle

  2. Použijte XEvent Profiler k zachycení dotazů na SQL Server

  3. Funkce STRING_AGG() v PostgreSQL

  4. Sledovací systém MySQL