DB2中多行转一列问题

来源:互联网 发布:沙袋绑腿 淘宝 编辑:程序博客网 时间:2024/06/06 00:30
有一张表 table1

月份     姓名      科目
----------------------------
200910   张三      英语
200910   张三      数学
200910   张三      语文
200910   李四      英语
200910   李四      体育


现在需要多行转成一列,把一个人选的科目在一个字段里列出来,用逗号隔开
出来的效果:

月份    姓名        所选科目
----------------------------------------
200910  张三       英语,数学,语文
200910  李四       英语,体育


需要这样的效果在DB2里怎么实现??


-------------------------------

http://topic.csdn.net/u/20100128/22/db7d3532-3bee-44da-9a45-1dc963294030.html?seed=1863118647&r=63088745#r_63088745
参照此贴
--------------------------------------------------------------------------------------------------------

 

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 
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  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 where t.id1= (select max(id1) from where s.iname = t.iname);
5.结果如下:
'x'    'bb,bb,aa'
'y'    'bb,bb,bb'
  

原创粉丝点击