create multiset volatile table t1 (
Pid int
,val char(10)
) on commit preserve rows;
insert into t1 values (1,’a’);
insert into t1 values (2,’b’);
insert into t1 values (3,’c’);
insert into t1 values (4,’d’);
with recursive c1 as (
Select. —驱动游标
pid
,val
,cast(val as varchar(100)) as pat
from t1
union all
Select
c1.pid+1
,t1.val
,trim(c1.pat)||trim(t1.val) —拼接结果需要Trim防止报错
From t1 inner join c1
On c1.pid=t1.pid
)
Select * from c1 order by 1,2;
—结果
—创建数据表(树形表)
Create multiset table vt1 (
ID int —主键
,pid int —上一个节点主键
,Val char(10) —值
) on commit primary index(id) preserve rows;
Insert into vt1 values (1,0,’a’);
Insert into vt1 values (2,1,’b’);
Insert into vt1 values (3,1,’c’);
Insert into vt1 values (4,2,’d’);
Insert into vt1 values (5,2,’e’);
Insert into vt1 values (6,2,’f’);
Insert into vt1 values (7,4,’g’);
with recursive cte as (
Select AD,PID,0 as level ,Val, cast(Val as char(200) ) as pat from vt1 where pid=0 —定位点(递归循环的开始位置)
Union all
select id,pid,cte.level+1 ,Val,trim(cte.pat)||’-’||trm(val) from cte join vt1 on cte.pid=vt1.pid
)
Select * from cte order by 1,2
;
—结果
create multiset volatile table table1 (
Org varchar(10)
,rk number(10)
,Val varchar(10)
) on commit preserve rows ;
insert into table1 values(‘’a总行,0,’’):
insert into table1 values(‘’b北京,1,’念’):
insert into table1 values(‘’b北京,2,‘奴’):
insert into table1 values(‘’b北京,3,’娇’):
insert into table1 values(‘’c上海,1,’卜’):
insert into table1 values(‘’c上海,2,’算’):
insert into table1 values(‘’c上海,3,’子’):
—处理思路
一轮迭代
—处理过程
create multiset volatile table vt1 as (
Select
Org
,rank() over(partition by 0 order by org ) as ID —机构排序,机构必须为非连续结果
,row_number() over(partition by 0 preserve by org,rk ) as PID —数据迭代ID
,Val
From table1
) on commit preserve rows
;
从驱动表开始,不断的去关联迭代表,将结果集并入驱动表,之后再由新的驱动表去关联迭代表,反复执行,直至关联结果为空是结束(一般不超过最大迭代数)
With recursive c1 as (
select —驱动表(行)
Org,ID,PID,VAL,cast(Val as varchar(100)) as Paths
From vt1 where ID=1
union all
select —迭代关联表
vt1.org,vt1.id+1 ,vt1.PID+1 ,vt1.val ,case where vt1.id=c1.PID then vt1.val else c1.paths || vt1.val end
From vt1
Inner join C1
On vt1.pid=c1.PID
)
select * from c1
Qualify row_number()over(partition by org order by PID desc)=1
;
—结果