|
数据内容为不可预测的,则需要借助存储过程或者函数来实现oracle行列转换
如下面所述的表内容,在name字段内容不确定时,合并相同id的那么值可以有两种实现方式,其一为利用函数,其二使用表变量并编写存储过程实现。下面描述了用函数实现的方式。
table1(id varchar2(10), name varchar2(10))
id name 1 aa 1 bb 1 cc 2 xx 3 yy 3 zz ...
想得到一个结果集如下: id names 1 aa+bb+cc 2 xx 3 yy+zz --建立测试环境
create table table1(
id varchar(3),
name varchar2(10)
);
--插入测试数据
insert into table1 values('001','sd');
insert into table1 values('001','vf');
insert into table1 values('001','rt');
insert into table1 values('002','3r');
insert into table1 values('002','gf');
insert into table1 values('003','vf');
insert into table1 values('003','hji');
--查看当前数据表内容
select * from table1;
commit;
create or replace function can_Table1(ASql varchar2)
return varchar2
is
type typ_cursor is ref cursor;
cur_table1 typ_cursor;
ATemp varchar2(10);
AResult varchar2(100):= '';
begin
open cur_table1 for ASql;
loop
fetch cur_table1 into ATemp;
exit when cur_Table1%notfound;
AResult := AResult || ATemp;
end loop;
return AResult;
end;
select id,can_table1('select name from table1 where id = '''||id||'''') from (select distinct id from table1) t;
|