《Teradata数据库递归子查询&跨行拼接》

《Teradata数据库递归子查询&跨行拼接》

SQL递归原理

  • A:原表S 和游标C ,目标表T,设定好游标作为驱动。
  • B:游标和目标表关联,结果插入T表,同时更新游标C。
  • C:用更细过的C再关联S表。
  • D:重复B,C直达返回结果为空(或到达递归最高次数)
  • E:递归结束后,返回T表

简单的迭代拼接

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;
—结果
《Teradata数据库递归子查询&跨行拼接》_第1张图片

实现树状结构遍历

—创建数据表(树形表)
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,’子’):

—处理思路

  • 样本数据中数据分两类,没一类有若干数据需要拼接,数据处理的关键在于生成俩个ID:机构(分组)ID和迭代ID
  • 迭代原理:驱动表去关联迭代表,每次关联的时候都会关联结果集(多次关联后的结果集)再去匹配迭代,最终不断拼接成目标表
  1. 为原数据生成两个ID
  2. 驱动语句和迭代语句关联,使得驱动表迭代ID不断增加,实现关联
  3. 当迭代ID和机构(分组)ID相同时,重置目标列,凯斯新

一轮迭代
—处理过程
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
;

—结果

你可能感兴趣的:(笔记)