![](/img/trans.png)
[英]Issue with self join with a sub query;wanted to know the difference of 2 queries below
[英]SQL query for 3 sub queries with self join
請提供一些建議,以實現以下所需的輸出。
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
只需使用聚合:
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;
嘗試一些條件聚合:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.