15

我有一张桌子

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

2 回答 2

32

这种类型的转换称为枢轴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

根据您的数据库,如果您可以访问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 |
于 2013-03-14T13:58:30.387 回答
4
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'
于 2013-03-14T14:11:14.947 回答