---
title: "db2中关于递归(with)的使用"
author: "zcb7288"
date: "2011-05-24T19:15:51Z"
tags: [".net", "Blog", "DB2"]
categories: ["数据库"]
slug: "db2-with"
draft: false
lastmod: "2011-05-24T19:19:04Z"
id: 1056941
url: "https://zcb7288.iteye.com/blog/1056941"
---

db2中关于递归(with)的使用

因为有人问及，这边简单的再探讨一下  
\-------------------  
1.创建测试表  
create table zxt\_test  
( id varchar(10),  
  ivalue varchar(20),  
  iname varchar(20)  
)  
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'

 

 

 

另外一种写法:

 

with  
s as (  
select row\_number() over(partition by iname order by id) id1, ivalue,iname from zxt\_test  
)  
,  
t(iname,id1,ivalue) as  
(  
select iname,id1,cast(ivalue as varchar(100)) from  s where id1 =1  
union all  
select t.iname,s.ID1,cast(s.ivalue||','||t.ivalue as varchar(100))  
from  s, t  
where   s.id1=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);

 

 

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