如何在sql中将两行合并为一行?

时间:2013-03-14 13:53:36

标签: sql pivot

我有一张桌子

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,但不确定如何在我的情况下使用它。

2 个答案:

答案 0 :(得分:24)

此类转换称为 pivot 。您没有指定正在使用的数据库,但您可以在任何系统中使用带有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函数创建四个新列:

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 |

答案 1 :(得分:3)

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'