Oracle:有条件地从LISTAGG中排除数据

时间:2014-09-04 12:41:19

标签: oracle11g

我有一个像这样的表结构:

username     reason   suspended  
1               X       0  
1           (null)      1  
1              Y        1  
2              Z        0  
2              P        1  
2           (null)      0  
2              Q        1  

我想做一个原因列的listagg和暂停列的总和,但我想从listagg和sum中排除那个特定的行,其中reason不是null并且suspend = 0.结果数据应该是这样的:

username    reason  suspended  
1              X        0  
1          (null);Y     1+1  
2              Z        0  
2       P;(null);Q      1+0+1  

请帮助(请原谅我格式不佳)

1 个答案:

答案 0 :(得分:0)

试试这个:

with t as (
  select 1 id, 'x' reason, 0 suspended from dual union all
  select 1, null, 1 from dual union all
  select 1, 'y', 1 from dual union all
  select 2 id, 'x', 0 reason from dual union all
  select 2, null, 1 from dual
)
select id
     , listagg(case when reason is null then '(null)' else reason end,';') within group(order by reason) res
     , listagg(cast(suspended as char), '+') within group(order by reason) res1
  from t
 where suspended != 0
 group by id
union
select id
     , reason
     , suspended || '' suspended
  from t
 where suspended = 0
order by id
/

了解它的工作原理:

SQL> ed
Wrote file afiedt.buf

  1  with t as (
  2    select 1 id, 'x' reason, 0 suspended from dual union all
  3    select 1, null, 1 from dual union all
  4    select 1, 'y', 1 from dual union all
  5    select 2 id, 'x', 0 reason from dual union all
  6    select 2, null, 1 from dual
  7  )
  8  select id
  9       , listagg(case when reason is null then '(null)' else reason end,';') within group(order by reason) res
 10       , listagg(cast(suspended as char), '+') within group(order by reason) res1
 11    from t
 12   where suspended != 0
 13   group by id
 14  union
 15  select id
 16       , reason
 17       , suspended || '' suspended
 18    from t
 19   where suspended = 0
 20* order by id
SQL> /

        ID RES                  RES1
---------- -------------------- --------------------
         1 x                    0
         1 y;(null)             1+1
         2 (null)               1
         2 x                    0