简体   繁体   中英

Oracle sql: Using two listagg

I'm using the following code to bring through 'DEL' text and 'PAL' text. The 'DEL' and 'PAL' text could be across several lines (and not necessarily the same amount of lines of each).

select trim(listagg(tx1.text, ', ') within group (order by tx1.text)) del_text,
trim(listagg(tx2.text, ', ') within group (order by tx2.text)) pal_text
from oes_ordtxt tx1
inner join oes_ordtxt tx2
    on tx1.key1 = tx2.key1
    and tx1.key2 = tx2.key2
    and tx1.key3 = tx2.key3
    and tx2.doctyp = 'PAL'
where tx1.key1 = '0018104834'
and tx1.key2 = '00001'
and tx1.key3 = '001'
and tx1.doctyp = 'DEL'

The problem I have is that where I have multiple rows on 'DEL text and only one row on 'PAL' text the 'PAL' text repeats, eg

在此处输入图片说明

The 'PAL_TEXT' is duplicating as only one PAL_TEXT exists but, three DEL_TEXT exists.

Is there a way to remove the duplicates?

Thanks, SMORF

It doesn't matter how many tables in aggregation (unfortunately I can't check syntax without your data structure):

select (select listagg(column_value,', ') within group (order by column_value) from table (del_text)) del_text
      ,(select listagg(column_value,', ') within group (order by column_value) from table (pal_text)) pal_text
from (select collect (distinct tx1.text) del_text,
             collect (distinct tx2.text) pal_text
      from oes_ordtxt tx1
      inner join oes_ordtxt tx2
         on tx1.key1 = tx2.key1
        and tx1.key2 = tx2.key2
        and tx1.key3 = tx2.key3
        and tx2.doctyp = 'PAL'
      where tx1.key1 = '0018104834'
        and tx1.key2 = '00001'
        and tx1.key3 = '001'
        and tx1.doctyp = 'DEL'
      group by 1)

Rewrite the select to

1) group both tables on the join key and calculate listagg (possible removing duplicate keys)

2) join the result

The join will be always 1:1, so there will be no duplication caused by it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM