有一Oracle表,内容如下:
name         alias        age
 张三          23
 李四          24
 王五
 卢芳         小芳
 操利               
 李焱
 季霞         小霞         22
 周中继       
 张延         张慎         
 孙起                     21
…………
…………我想把name字段中的各个值用“,”连接起来,怎么办呢?
比如上表的结果应该是:
张三,李四,王五,卢芳,…………这样的SQL语句怎样写呢?

解决方案 »

  1.   

    参考SQL> select * from test;ID TME---- ----------A 1B 1C 1D 1E 1F 2G 2已选择7行。SQL> select tme, substr(max(sys_connect_by_path(id, ',')), 2) catstr2 from (select id, tme, row_number() over(partition by tme order by 1) rn3 from test)4 start with rn = 15 connect by rn - 1 = prior rn and tme = prior tme6 group by tme;TME CATSTR---------- --------------------1 A,B,C,D,E2 F,GSQL> 
      

  2.   

    也可以写个函数
    参考--测试数据
    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