我想根据ratetype
和costtype
列来调整以下数据。我似乎无法弄清楚如何做到这一点,没有将ratetype
和costtype
值连接在一起,然后对此进行调整......
可以做得更好吗?
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
答案 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