這種類型的轉換被稱爲樞軸。您沒有指定您所使用的數據庫,但你可以在任何系統中使用聚合函數與CASE
表達:
select employeeid,
max(case when IsActive = 'true' then IndividualPay end) IndPay_IsActive,
max(case when IsActive = 'false' then IndividualPay end) IndPay_IsNotActive,
max(case when IsActive = 'true' then FamilyPay end) FamilyPay_IsActive,
max(case when IsActive = 'false' then FamilyPay end) FamilyPay_IsNotActive
from yourtable
group by employeeid
見SQL Fiddle with Demo
根據您的數據庫,如果你有機會到兩個PIVOT
和UNPIVOT
函數,那麼它們可以用來得到結果。 UNPIVOT
函數將IndividualPay
和FamilyPay
列轉換爲行。一旦做到這一點,那麼你就可以創建一個PIVOT
功能的4個新列:
select *
from
(
select employeeid,
case when isactive = 'true'
then col+'_IsActive'
else col+'_IsNotActive' end col,
value
from yourtable
unpivot
(
value
for col in (IndividualPay, FamilyPay)
) unpiv
) src
pivot
(
max(value)
for col in (IndividualPay_IsActive, IndividualPay_IsNotActive,
FamilyPay_IsActive, FamilyPay_IsNotActive)
) piv
見SQL Fiddle with Demo。
都給予同樣的結果:
| EMPLOYEEID | INDIVIDUALPAY_ISACTIVE | INDIVIDUALPAY_ISNOTACTIVE | FAMILYPAY_ISACTIVE | FAMILYPAY_ISNOTACTIVE |
----------------------------------------------------------------------------------------------------------------
| 1 | 200 | 100 | 300 | 150 |
是的,你想有一個支點查詢,但語法通過數據庫系統而異。你在用哪個? – Alkini 2013-03-14 13:57:08