这种类型的转换称为枢轴。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
根据您的数据库,如果您可以访问PIVOT
和UNPIVOT
函数,则可以使用它们来获取结果。该UNPIVOT
函数将IndividualPay
和FamilyPay
列转换为行。完成后,您可以使用以下函数创建四个新列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 |