[英]Oracle SQL - Combine values in the same column in one column in the result set from multiple table
我很想知道如何合並來自兩個不同表的同一列中的多個記錄。 例如下面是我的表:
注釋表:
INVOICE NOTES
1000 REPLACE PUMP
1000 REPLACE OIL
1000 REPLACE FILTER
1111 WO# 123
1111 REPLACE GASKET
1234 REPLACE OIL
發票表:
INVOICE AMOUNT
1000 100
1111 50
1234 20
我可以運行此查詢和結果:
SELECT INV.INVOICE, INV.AMOUNT FROM INVOICE INV
INNER JOIN NOTES ON INV.INVOICE = NOTES.INVOICE
但我想將每個發票的注釋合並到結果集中的一欄中。 例如,我的結果應如下所示
INVOICE AMOUNT NOTES
1000 100 REPLACE PUMP, REPLACE OIL, REPLACE FILTER
1111 50 WO# 123,REPLACE GASKET
1234 20 REPLACE OIL
詢問
with inv_notes as
(select 1000 as INVOICE, 'REPLACE PUMP' as notes from dual union all
select 1000, 'REPLACE PUMP' from dual union all
select 1000, 'REPLACE OIL' from dual union all
select 1000, 'REPLACE FILTER' from dual union all
select 1111, 'WO# 123' from dual union all
select 1111, 'REPLACE GASKET' from dual union all
select 1234, 'REPLACE OIL' from dual
)
,
inv_amount as (
select 1000 as INVOICE, 100 AMOUNT from dual union all
select 1111, 50 from dual union all
select 1234, 20 from dual)
select a.invoice, a.amount, listagg(n.notes, ',') WITHIN GROUP (ORDER BY a.invoice, a.amount) notes
from inv_notes n
inner join inv_amount a on n.invoice = a.invoice
group by a.invoice, a.amount
結果
1 1000 100 REPLACE FILTER,REPLACE OIL,REPLACE PUMP,REPLACE PUMP
2 1111 50 REPLACE GASKET,WO# 123
3 1234 20 REPLACE OIL
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.