有一Oracle表,内容如下:
name alias age
张三 23
李四 24
王五
卢芳 小芳
操利
李焱
季霞 小霞 22
周中继
张延 张慎
孙起 21
…………
…………我想把name字段中的各个值用“,”连接起来,怎么办呢?
比如上表的结果应该是:
张三,李四,王五,卢芳,…………这样的SQL语句怎样写呢?
name alias age
张三 23
李四 24
王五
卢芳 小芳
操利
李焱
季霞 小霞 22
周中继
张延 张慎
孙起 21
…………
…………我想把name字段中的各个值用“,”连接起来,怎么办呢?
比如上表的结果应该是:
张三,李四,王五,卢芳,…………这样的SQL语句怎样写呢?
参考--测试数据
create table tbale1(no int, content varchar2(100));
insert into tbale1
select 1,'aa' from dual union all
select 1,'bb' from dual union all
select 1,'cc' from dual union all
select 2,'mm' from dual union all
select 2,'nn' from dual union all
select 3,'oo' from dual;
--建立函数
create or replace function sum_string(v_sql varchar2)
return varchar2
as
type cur_alldata is ref cursor;
l_alldata cur_alldata;
v_row varchar2(99);
v_sum varchar2(3999);
begin
open l_alldata for v_sql;
loop
fetch l_alldata into v_row;
exit when l_alldata%notfound;
v_sum := v_sum||','||v_row;
end loop;
v_sum := substr(v_sum,2);
close l_alldata;
return v_sum;
end;
--执行查询
select distinct no,sum_string('select content from tbale1 where no='''||no||''' group by no,content') from tbale1
--执行结果
1 aa,bb,cc
2 mm,nn
3 oo