db2关于with递归使用

本文通过创建测试表并插入数据,演示了如何在 Oracle 中使用 WITH 语句进行复杂查询,实现对特定数据集的聚合操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[php]
---------

在with在oracle中称为家族树!pub中oracle模块对此类的使用已经很成熟!

因为有人问及,这边简单的再探讨一下
-------------------
1.创建测试表
create table zxt_test
( id varchar(10),
  ivalue varchar(20),
  iname varchar(20)
)
not logged initially;

commit;
-----------
2.插入测试语句
insert into zxt_test values('1','aa','x'),('2','bb','x'),('3','bb','x'),('1','bb','y'),('2','bb','y'),('3','bb','y');
commit;
---------------
3.查看数据
select * from zxt_test;
1        'aa'        'x'
2        'bb'        'x'
3        'bb'        'x'
1        'bb'        'y'
2        'bb'        'y'
3        'bb'        'y'
----------------
4.with 的写法!
with 
s as (
select row_number()over(partition by iname order by id) id1,
       row_number()over(partition by iname order by id) id2,
       ivalue,iname from zxt_test
)
,
t(iname,id1,id2,ivalue) as
(
select iname,id1,id2,cast(ivalue as varchar(100)) from  s where id1 =1 and id2=1
union all 
select t.iname,t.id1+1,t.id2,cast(s.ivalue||','||t.ivalue as varchar(100)) 
from  s, t 
where   s.id2=t.id1+1 and t.iname = s.iname 
)
select iname,ivalue from t where t.id1= (select max(id1) from s where s.iname = t.iname);
5.结果如下:
'x'        'bb,bb,aa'
'y'        'bb,bb,bb'

 

文章链接:http://www.itpub.net/thread-881890-1-1.html

有更详细的请查看我的blog!
http://myfriend2010.itpub.net/post/29012/367738

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值