2017-12-01 1 views
1

Ich möchte die folgenden Daten basierend auf den ratetype und Spalten spalten. Ich kann anscheinend nicht herausfinden, wie man das macht, ohne vielleicht die Werteund costtype zusammen zu verketten, dann einen Drehpunkt auf diesem ...SQL Pivot basiert auf zwei "für" Spalten

Kann es ein besserer Weg getan werden?

Employee Period RateType CostType Value 
-------------------------------------------- 
1   201701 Rate1  CostA  500 
1   201701 Rate1  CostB  700 
1   201701 Rate2  CostA  400 
1   201701 Rate2  CostB  200 

in

Employee Period Rate1CostA Rate1CostB Rate2CostA Rate2CostB 
------------------------------------------------------------------- 
1   201701 500   700   400   200 

Die einzige Art, wie ich herausfinden kann es mit zu tun, indem zuerst die beiden Felder verketten, was hässlich fühlt. So etwas wie ...

SELECT 
    Employee, 
    Period, 
    Rate1CostA, Rate1CostB, 
    Rate2CostA, Rate2CostB 
FROM 
    (SELECT 
     Employee, 
     Period, 
     RateType + CostType as RateCostType, 
     Value 
    FROM 
     MyTable) CostRate 
PIVOT 
    (MAX(Value) 
     FOR RateCostType IN (Rate1CostA, Rate1CostB, Rate2CostA, Rate2CostB) 
    ) AS p 
+0

Woops, Sie sind richtig, ich bin mit MSSQL, ich werde die Tags aktualisieren – kralco626

Antwort

3

bedingte Aggregation ist ein Ansatz:

SELECT Employee, Period, 
     MAX(CASE WHEN RateType = 'Rate1' AND CostType = 'CostA' 
       THEN Value 
      END) Rate1CostA, 
     MAX(CASE WHEN RateType = 'Rate1' AND CostType = 'CostB' 
       THEN Value 
      END) Rate1CostB, 
     MAX(CASE WHEN RateType = 'Rate2' AND CostType = 'CostA' 
       THEN Value 
      END) Rate2CostA, 
     MAX(CASE WHEN RateType = 'Rate2' AND CostType = 'CostB' 
       THEN Value 
      END) Rate2CostB 
FROM YourTable 
GROUP BY Employee, Period