如何在SQL中将两行合并为一行? [英] How to merge two rows into one row in sql?

查看:1346
本文介绍了如何在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小提琴

取决于您的数据库,如果您可以同时访问PIVOTUNPIVOT函数,则可以使用它们来获取结果. UNPIVOT函数将IndividualPayFamilyPay列转换为行.完成后,您可以使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆