Oracle SQL中的ListAgg(基于2个表)

时间:2019-02-28 03:52:22

标签: sql oracle

我的解释如下。

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

运行这些代码时,我收到了错误消息:“从只允许一列的子查询返回多列”。

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

2 个答案:

答案 0 :(得分:0)

假设您的示例输入由于错字而错了,这个简单的查询应该对您有用

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;

答案 1 :(得分:0)

您的问题有以下问题,首先是第一部分EXPORT_SHIPMENT中的表名(我认为其中有下划线),而EVENT_CODE与您提供的代码段不匹配。您是否还在尝试将行号合并到“文件号”字段中?很难确定您要寻找什么。

对于原始错误,Oracle相关子查询不支持多列。这是导致该错误的原因,您可以返回ee.remarksrow_number(),不能同时返回两者。

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'

对于您想要的东西,我的最佳猜测是这样的,请注意,我在联接表时没有尝试子查询。

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