ITPub博客

首页 > Linux操作系统 > Linux操作系统 > 不规则的行转列

不规则的行转列

原创 Linux操作系统 作者:tsai_vogue 时间:2013-01-10 13:55:10 0 删除 编辑
需求:
t1表:
id name 
1    柜子
2    窗帘
3    电脑

t2表:
id table1id labelname
1    1        红色
2    1        家用
3    1        绿色
4    2        红色
5    2        家用
6    3        笔记本
7    3        台式机
8    3        红色

要显示为:
id   name  labelname
1 柜子 家用,红色,绿色
2 窗帘 家用,红色
3 电脑 台式机,笔记本,红色

语句:
create table t1(id number,name varchar2(10));
create table t2(id number,table1id number,labelname varchar2(10));

insert into t1 values(1,'柜子');
insert into t1 values(2,'窗帘'):
insert into t1 values(3,'电脑'):

insert into t2 values(1,1,'红色');
insert into t2 values(2,1,'家用');
insert into t2 values(3,1,'绿色');
insert into t2 values(4,2,'红色');
insert into t2 values(5,2,'家用');
insert into t2 values(6,3,'笔记本');
insert into t2 values(7,3,'台式机');
insert into t2 values(8,3,'红色');

方法1 利用函数wm_concat:
select id,name,attribute from(
select a.id,a.name,wm_concat(b.labelname) attribute from t1 a,t2 b where a.id=b.table1id
group by a.name)

方法2 利用函数listagg:
select id,name,listagg(labelname,',') within group(order by labelname) labelname from  (select a.id,a.name,b.labelname from t1 a,t2 b where a.id=b.table1id) group by id,name;

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/26918004/viewspace-752453/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: oracle 约束
下一篇: connect by的应用
请登录后发表评论 登录
全部评论

注册时间:2012-12-19

  • 博文量
    10
  • 访问量
    13110