SQL将两个记录合并为一个

时间:2015-03-05 18:19:29

标签: sql oracle11g

我正在使用的表使用两行来记录每个事务':一行用于识别行动方,第二行用于识别当事人所采取的行动。数据内容的区别仅在于一个字段的值,一个逻辑标志是' Y'或者' N'例如,我可能会这样:

E-num  E-date       Client   Actor
1234   2013-05-02   ACME     Y
1234   2013-05-02   ALLIED   N

我想报告的是:

E-num  E-date       For      Against
1234   2013-05-02   ACME     ALLIED

谢谢,伙计们。 特里

3 个答案:

答案 0 :(得分:1)

只需加入E-num上的表格,然后根据需要选择行。

如果您使用的是MySQL,那么查询将是

   SELECT
     t1.E-num,
     t1.E-date,
     t1.Client AS 'For',
     t2.Client AS Against
   FROM
     `transaction` t1
   INNER JOIN
     `transaction` t2
   ON 
     t1.E-num = t2.E-num
   WHERE
     t1.Actor = 'Y' AND
     t2.Actor = 'N'

未测试,但它应该给你一个想法。

答案 1 :(得分:0)

ORACLE版本:使用表格的自联接:

SELECT t1."E-num", t1."E-date", t1."Client" as "For", t2."Client" as "Against"
  FROM transaction t1, transaction t2
 WHERE t1."E-num"  = t2."E-num"
   AND t1."E-date" = t2."E-date"
   AND t1."Actor" = 'Y'
   AND t2."Actor" = 'N';

答案 2 :(得分:0)

你可以使用pivot ...

with t as (
    select [E-num] = 1234, [E-date] = '5/2/2013', [Client] = 'ACME', Actor = 'Y'
    union select 1234, '5/2/2013', 'ALLIED', 'N'
)

select
    p.[E-num],
    p.[E-date],
    [For] = p.[Y],
    [Against] = p.[N]
from
    t
    pivot (
        max(Client)
        for Actor in ([Y],[N])
    ) p