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