SQL pivot基于两个“for”列

时间:2017-12-01 20:27:18

标签: sql sql-server sql-server-2012

我想根据ratetypecosttype列来调整以下数据。我似乎无法弄清楚如何做到这一点,没有将ratetypecosttype值连接在一起,然后对此进行调整......

可以做得更好吗?

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

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

我可以通过首先连接两个字段来解决这个问题的唯一方法,这感觉很难看。有点像...

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

1 个答案:

答案 0 :(得分:3)

条件聚合是一种方法:

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