sql >> Database teknologi >  >> RDS >> Sqlserver

Multi Column Pivot SQL Server

Hvis værdierne ABC og XYG er kendt på forhånd, kan du lave betinget aggregering

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

Eksempeloutput:

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

Her er SQLFiddle demo




  1. MySQL-ydelse:Sådan udnytter du MySQL-databaseindeksering

  2. SQL-forespørgselsoptimering:Bedste fremgangsmåder for forbedret ydeevne

  3. Hvordan kan jeg ændre en primær nøglebegrænsning ved hjælp af SQL-syntaks?

  4. MySQL-forespørgsel returnerer duplikerede rækker