2013-03-14 80 views
7

我有一個表作爲如何在sql中將兩行合併成一行?

EmployeeID IndividualPay FamilyPay IsActive 
    1   200   300  true 
    1   100   150  false 

但我想輸出如下(我想內與其他表連接使用此輸出)

EmployeeID IndPay_IsActive IndPay_IsNotActive FamilyPay_IsActive FamilyPay_IsNotActive 
    1   200     100    300     150 

我已經調查PIVOT,但不知道如何在我的情況下使用它。

+4

是的,你想有一個支點查詢,但語法通過數據庫系統而異。你在用哪個? – Alkini 2013-03-14 13:57:08

回答

21

這種類型的轉換被稱爲樞軸。您沒有指定您所使用的數據庫,但你可以在任何系統中使用聚合函數與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

根據您的數據庫,如果你有機會到兩個PIVOTUNPIVOT函數,那麼它們可以用來得到結果。 UNPIVOT函數將IndividualPayFamilyPay列轉換爲行。一旦做到這一點,那麼你就可以創建一個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 | 
+0

我不是那個低調的人,但你的案例結構對我來說看起來不完整。他們沒有「其他」部分。 – 2013-03-14 14:01:59

+1

@DanBracuk使用'CASE'時不需要'else',它不包括在內,那麼'null'將被放置在列中。 – Taryn 2013-03-14 14:02:44

+1

此解決方案適用於我..感謝您的快速響應。 – user1882705 2013-03-14 14:03:40

2
Select 
    EmployeeID, 
    Active.IndividualPay As IndPay_IsActive, 
    Active.FamilyPay As FamilyPay_IsActive, 
    Inactive.IndividualPay As IndPay_IsNotActive, 
    Inactive.FamilyPay As FamilyPay_IsNotActive 
From 
    PayTable Active 
    Join PayTable Inactive On Active.EmployeeID = Inactive.EmployeeId 
     And Inactive.IsActive = 'false' 
Where 
    Active.IsActive = 'true'