2014-09-04 56 views
0

排除數據我有一個表的結構是這樣的:甲骨文:有條件地LISTAGG

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特定行和,其中的原因不爲空,懸浮= 0所得到的數據應該是這樣的:

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

好心幫(請原諒我的格式化差)

+0

閱讀[這](http://tkyte.blogspot.de/2005/06/how-to-ask-questions.html)找出請問如何提問 – zaratustra 2014-09-04 13:35:52

回答

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