oracle列转行以及一行转多行

--创建临时表存储用户办理套餐信息
create table tmp_20200621
(
   user_id      number(20),
   dou_disc_id  number(10),
   dou_disc_name varchar2(600),
   dou_disc_fee  number(18,2)
);

insert into tmp_20200621
values
(
   123456,
   14,
   '微博客户端',
   60.00
);

oracle列转行以及一行转多行_第1张图片

--使用listagg函数将列转为行
create table tmp_20200621_01 as 
select 
user_id,
listagg(dou_disc_id,';') within group(order by dou_disc_id) as dou_disc_id,
listagg(dou_disc_name,';') within group(order by dou_disc_id) as dou_disc_nam,
listagg(dou_disc_fee,';') within group(order by dou_disc_id) as dou_disc_fee
from tmp_20200621
group by user_id;

select * from tmp_20200621_01;

**使用listagg函数将列转为行**

--将一行转为多行
drop table tmp_20200621_02;
create table tmp_20200621_02 as 
select 
user_id,
regexp_substr(dou_disc_id,'[^;]+',1,level) as dou_disc_id
/*regexp_substr(dou_disc_name,'[^;]',1,rn) as dou_disc_name,
regexp_substr(dou_disc_fee,'[^;]',1,sn) as dou_disc_fee*/
from tmp_20200621_01
connect by level<=length(dou_disc_id)-length(regexp_replace(dou_disc_id,';',''))+1;
           
select * from tmp_20200621_02;

oracle列转行以及一行转多行_第2张图片

你可能感兴趣的:(数据库开发,sql)