简体   繁体   中英

ListAgg in Oracle sql (based on 2 tables)

My explanation as below.

BRDB.EXPORT SHIPMENT (table)

 SHPMNT_REF  | SHIPMENT_TYPE
    867      | EHH
    868      | EHH
    869      | EHH

BRDB.EVENT_CODE (table)

 FILE_NO  | REMARKS   EVENT_CODE
 867      | TEST0      SIR
 867      | TEST1      SIR
 867      | TEST2      SIR
 867      | TEST3      SIR
 868      | TEST4      EEO

I want my report is showing as below

  FILE NO    |  REMARKS
     123     |  TEST0,TEST1,TEST2
     456     |  TEST3

I have received error when running these code "Multiple columns are returned from a subquery that is allowed only one column".

select min(X.SHPMNT_REF) as "House B/L #",
       listagg(case when SIR = 1 then X.REMARKS end, ',') within group (order by X.SHPMNT_REF) as "REMARKS(from SIR Event)"
FROM   (select ES.SHPMNT_REF,
               (select EE.REMARKS,
                       row_number() over (order by EE.FILE_NO)
                FROM   BRDB.EXPORT_EVENT EE
                where  EE.FILE_NO = ES.SHPMNT_REF
                and    EE.EVENT_CODE = 'SIR') as SIR
        from   BRDB.EXPORT_SHIPMENT ES)X
GROUP BY X.SHPMNT_REF

Assume your sample input is wrong by typo, this simple query should work for you

SELECT file_no, 
    LISTAGG(remarks, ',') WITHIN GROUP (ORDER BY remarks) AS remarks
FROM brdb.event_code
WHERE event_code = 'SIR'
GROUP BY file_no
ORDER BY file_no;

Your question has the following issues, firstly the table names in the first part EXPORT_SHIPMENT (I assume there's an underscore in there) and EVENT_CODE do not match the code snippet you provided. Also are you trying to combine the row numbers into the file no field? Very hard to determine what you are looking for.

For the original error, Oracle correlated subqueries do not support multiple columns. This is causing that error, you can return ee.remarks or row_number() , not both.

select EE.REMARKS,
row_number() over (order by EE.FILE_NO)
from   BRDB.EXPORT_EVENT EE
where  EE.FILE_NO = ES.SHPMNT_REF
and    EE.EVENT_CODE = 'SIR'

My best guess for the what you want is something like this, notice that I am joining the tables not trying a subquery.

select X.FILE_NO 
       ,listagg(X.REMARKS || ',') within group (order by X.SHPMNT_REF) 
       ,listagg(X.ROW_NUM) within group (order by X.SHPMNT_REF) 

FROM  
(
    select EE.FILE_NO,
           ES.SHPMNT_REF,
           EE.REMARKS,
           row_number() over (order by EE.FILE_NO) as ROW_NUM
    FROM   EVENT_CODE       EE
    JOIN   EXPORT_SHIPMENT  ES
      ON   EE.FILE_NO = ES.SHPMNT_REF
    AND    EE.EVENT_CODE = 'SIR'
) X
group by X.FILE_NO

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