1,一行转多行
select t.vl,regexp_substr(t.vl,'[^;]+',1,L) as vl,L from
(select 'A;B;C;D' vl from dual) t,--模拟数据
(select level L from dual connect by level<=20)
where L(+)<=length(t.vl)-length(replace(t.vl,';'))+1
结果:
2,多行转一列
select t.id ,listagg(t.vl,';') within group (order by t.id) v
from (
select 'A' vl,1 id from dual
union all
select 'B' vl,1 id from dual
union all
select 'C' vl,2 id from dual
union all
select 'D' vl,2 id from dual)t
group by t.id
结果:
3,多行转多列
select decode(instr(rs.vl,'1!'),0,null,substr(substr(rs.vl,instr(rs.vl,'1!')+2),1,instr(substr(rs.vl,instr(rs.vl,'1!')+2),';')-1)) c1,
decode(instr(rs.vl,'2!'),0,null,substr(substr(rs.vl,instr(rs.vl,'2!')+2),1,instr(substr(rs.vl,instr(rs.vl,'2!')+2),';')-1)) c2,
decode(instr(rs.vl,'3!'),0,null,substr(substr(rs.vl,instr(rs.vl,'3!')+2),1,instr(substr(rs.vl,instr(rs.vl,'3!')+2),';')-1)) c3,
decode(instr(rs.vl,'4!'),0,null,substr(substr(rs.vl,instr(rs.vl,'4!')+2),1,instr(substr(rs.vl,instr(rs.vl,'4!')+2),';')-1)) c4
from(
select listagg(id || '!' || t.vl || ';','') within group (order by t.id) vl
from (
select 'A' vl,1 id from dual
union all
select 'B' vl,2 id from dual
union all
select 'C' vl,3 id from dual
union all
select 'D' vl,4 id from dual)t
)rs
结果: