簡體   English   中英

Oracle LISTAGG DISTINCT 與多個條件

[英]Oracle LISTAGG DISTINCT with multiple conditions

對於 Oracle12,我有如下所示的表格

ID 聯系代碼 聯系人
1 X 客戶
1 X 客戶
1 X 妻子
1 客戶
1 Z 妻子
1 Z 客戶
1 Z 丈夫
1 W 客戶
2 孩子
2 妻子
2 客戶
3 丈夫
3 W 客戶

我想要這樣的結果:

  • 聯系人是客戶。 如果 CONTACTCODE 在 (X,Y,Z) 然后列出所有不同的 CONTACTCODE ( 例如: X,Y,...) else 0 ( MAIN 列)
  • 聯系人 <> 客戶。 如果 CONTACTCODE 在 (X,Y,Z) 中,則列出所有不同的 CONTACTCODE(例如:X,Y,...)否則 0(REF 列)

預期表:

ID 主要的 參考
1 X,Y,Z X,Z
2
3 0

我使用按 ID、CONTACTCODE 和 LISTAGG 的 row_number 分區,其中 row_number = 1 但我遇到了很多問題。

您可以使用distinctcase..whenLISTAGG ,如下所示:

select id, 
       coalesce(listagg(case when isclient = 'CLIENT' then contactcode end,',') 
                  within group (order by contactcode), '0') as maincode,
       coalesce(listagg(case when isclient = 'NOT CLIENT' then contactcode end,',') 
                  within group (order by contactcode), '0') as ref 
(select distinct id, contactcode, 
        case when contactperson = 'CLIENT' then 'CLIENT' else 'NOT CLIENT' end as isclient
  from your_table t
 where t.contactcode in ('X', 'Y', 'Z') ) t
 group by id

您可以使用row_number()和條件聚合:

select id,
       (case when sum(case when contactperson = 'Client' then 1 else 0 end) > 0
             then listagg(case when seqnum = 1 and contactcode in ('X', 'Y', 'Z')
                               then contactcode
                          end, '') within group (order by contactcode)
        end),
       listagg(case when seqnum = 1 and contactcode in ('X', 'Y', 'Z')
                    then contactcode
               end, '') within group (order by contactcode)
from (select t.*,
             row_number() over (partition by id, contactcode order by id) as seqnum
      from t
     ) t
group by id

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM