具有自联接的3个子查询的SQL查询

时间:2016-01-15 13:23:58

标签: sql oracle

请提供一些建议如何达到以下要求的输出。

Table1 data
-----------
request_id    record_type  invoice_number      merchant_info          transaction_info
----------    -----------  -----------------   ----------------    -----------------------
123             01              NULL                NULL                  Trans1
123             30              NULL                Merc1                  NULL
123             02              Invoice1            NULL                   NULL
123             01              NULL                NULL                   Trans2
123             30              NULL                Merc2                  NULL
123             02              Invoice2            NULL                   NULL
124             01              NULL                NULL                  Trans3
124             30              NULL                Merc3                 NULL
124             02              Invoice3            NULL                   NULL
124             01              NULL                NULL                   Trans4
124             30              NULL                Merc4                  NULL
124             02              Invoice4            NULL                   NULL

必需的输出

---------------
invoice_number      merchant_info          transaction_info
--------------     --------------           -----------------
Invoice1             Merc1                     Trans1
Invoice2             Merc2                     Trans2
Invoice3             Merc3                     Trans3
Invoice4             Merc4                     Trans4



SELECT xpt.transaction_info,XTG.merchant_info,x.invoice_number
FROM (select * from table1
WHERE record_type='01' )xpt,
 (SELECT *
 FROM table1
 WHERE record_type='30'
 ) XTG,
 (SELECT *
 FROM table1
 WHERE record_type='02'
 and invoice_number is not null
 ) X
 WHERE 1=1 
 and xtg.request_id=xpt.request_id
and x.request_id=xpt.request_id

2 个答案:

答案 0 :(得分:1)

只需使用聚合:

select request_id, max(invoice_number) as invoice_number,
       max(merchant_info) as merchant_info,
       max(transaction_info) as transaction_info
from table1
group by request_id;

答案 1 :(得分:1)

尝试一些条件聚合:

select max (decode ( record_type, '01', transaction_info, null)) as transaction_info, 
       max (decode ( record_type, '30', merchant_info,    null)) as merchant_info,
       max (decode ( record_type, '02', invoice_number,   null)) as invoice_number
from table1
group by request_id