在同一表格中的ID上关联交易

时间:2019-06-27 11:45:04

标签: sql oracle

我有一个带有以下字段的交易表:

TRAN_ID    DATE     ACCNT_ID    NAME      AMOUNT    TRAN_TYPE

对于给定的交易,它借记一个客户的帐户并贷记另一个客户的帐户,我可以拥有:

客户1

TRAN_ID    DATE     ACCNT_ID     NAME      AMOUNT    TRAN_TYPE
0000001   10/10/17     AA1     Joe Burns     50        Debit

客户2:

TRAN_ID    DATE     ACCNT_ID     NAME      AMOUNT    TRAN_TYPE
0000001   10/10/17     AA2     Mary Adams    50        Credit

是否可以在此表上进行联接,以显示交易ID,发送者,接收者和金额?

3 个答案:

答案 0 :(得分:1)

您可以这样尝试,自行加入表格,其中一张用于借记,另一张用于借记,

SELECT R.NAME as RECIEVER,S.NAME as SENDER,R.AMOUNT as AMOUNT
FROM
        (Select * from
        Table
        where TRAN_TYPE='Debit') as R
        INNER JOIN
        (Select * from
        Table
        where TRAN_TYPE='Credit') as S
        on R.TRAN_ID=S.TRAN_ID

答案 1 :(得分:0)

我想是自我加入:

SQL> with tran (tran_id, datum, accnt_id, name, amount, tran_type) as
  2    (select '001', date '2017-10-10', 'aa1', 'Joe Burns' , 50, 'Debit' from dual
  3     union all
  4     select '001', date '2017-10-10', 'aa2', 'Mary Adams', 50, 'Credit' from dual
  5    )
  6  -- self-join
  7  select c.tran_id, c.datum, c.name credit_name, d.name debit_name, c.amount
  8  from tran c join tran d on c.tran_id = d.tran_id
  9       and c.tran_type = 'Credit'
 10       and d.tran_type = 'Debit';

TRA DATUM    CREDIT_NAM DEBIT_NAME     AMOUNT
--- -------- ---------- ---------- ----------
001 10.10.17 Mary Adams Joe Burns          50

SQL>

答案 2 :(得分:0)

您可以进行自我加入:

select tr.tran_id, tr.name as receiver, ts.name as sender,
       tr.amount
from transactions tr join
     transactions ts
     on tr.tran_id = ts.tran_id and
        tr.tran_type = 'credit' and
        ts.tran_type = 'debit';

请注意,这不会检查amountdate列是否相同。而且,它仅返回同时具有两个记录的交易。