如何在SQL中将两行合并为一行? [英] How to merge two rows into one row in sql?
问题描述
我有一张桌子
EmployeeID IndividualPay FamilyPay IsActive
1 200 300 true
1 100 150 false
但是我希望输出如下(我想使用此输出与其他表进行内部联接)
But I want the output as follows(I want to use this output to inner join with some other table)
EmployeeID IndPay_IsActive IndPay_IsNotActive FamilyPay_IsActive FamilyPay_IsNotActive
1 200 100 300 150
我已经研究过PIVOT
,但不确定如何使用它.
I have looked into PIVOT
, but not sure how to use it in my case.
推荐答案
这种类型的转换称为数据透视.您没有指定要使用的数据库,但是可以在任何系统中使用带有CASE
表达式的聚合函数:
This type of transformation is known as a pivot. You did not specify what database you are using but you can use an aggregate function with a CASE
expression in any system:
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小提琴
取决于您的数据库,如果您可以同时访问PIVOT
和UNPIVOT
函数,则可以使用它们来获取结果. UNPIVOT
函数将IndividualPay
和FamilyPay
列转换为行.完成后,您可以使用PIVOT
函数创建四个新列:
Depending on your database, if you have access to both the PIVOT
and UNPIVOT
functions, then they can be used to get the result. The UNPIVOT
function converts the IndividualPay
and FamilyPay
columns into rows. Once that is done, then you can create the four new columns with the PIVOT
function:
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小提琴.
两者给出的结果相同:
| EMPLOYEEID | INDIVIDUALPAY_ISACTIVE | INDIVIDUALPAY_ISNOTACTIVE | FAMILYPAY_ISACTIVE | FAMILYPAY_ISNOTACTIVE |
----------------------------------------------------------------------------------------------------------------
| 1 | 200 | 100 | 300 | 150 |
这篇关于如何在SQL中将两行合并为一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!