首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > IBM DB2 >

急求DB2的一句sql 大神们回逛逛啦。

2013-07-01 
急求DB2的一句sql大神们来逛逛啦。。。我有一张表test如下:idcodename1111zhangsan2222lisi3333wangwu4111xia

急求DB2的一句sql 大神们来逛逛啦。。。
我有一张表test  如下:

id      code    name  
1       111    zhangsan
2       222     lisi
3       333    wangwu
4       111   xiaoliuzi

我想要查询出来的结果如下 :
id      code    name  
1       111    zhangsan,xiaoliuzi
2       222     lisi
3       333    wangwu

就是将code相同的name拼接在一起  用一条数据来显示出来。 


DB2 SQL 行业数据
[解决办法]
select code, 
        replace(
        replace(
        replace(
            xmlserialize(XMLAGG(XMLELEMENT(NAME "x", id) ) as varchar(1000))
            , '</x><x>', ',')
            , '<x>', '')
            , '</x>', '') as ids 
    from myTable
    group by code;
[解决办法]
示例:
b2中关于递归(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'

热点排行