方法一:wmsys.wm_concat(column)
介绍:其函数在Oracle 10g推出,在10g版本中,返回字符串类型,在11g版本中返回clob类型。括号里面的参数是列,而且可以是多个列的集合,也就是说在括号里面可以自由地用‘||’合并字符串。如下面的例子:
Select 分组字段 , wmsys.wm_concat(连接字符串字段) from 表名 group by 分组字段
wmsys.wm_concat例子 :
WITH temp1 AS(
select 'a' as username,1 as deptid from dual union all
select 'b',1 from dual union all
select 'c',1 from dual union all
select 'd',2 from dual union all
select 'e',2 from dual
),
temp2 AS(
select 1 as deptid,'部门1' as deptname from dual union all
select 2 ,'部门2' from dual
)
select p.deptid,
wm_concat(t.username) as username,
p.deptname
from temp1 t,temp2 p
where t.deptid=p.deptid
group by p.deptid,p.deptname
order by p.deptid
方法二:listagg (column,[,]) within group (order by ) [over (partition by )]
介绍:其函数在Oracle 11g 版本中推出,对分组后的数据按照一定的排序进行字符串连接。其中,“[,]”表示字符串连接的分隔符,如果选择使用[over (partition by )]则会使其变成分析函数;
SELECT
分组字段 ,
listagg(连接字段,',') within group (order by 排序字段)
FROM 表名
group by 分组字段
--注:连接字段和分组字段可以使用同一个
listagg 例子 : listagg(t.username,’,’) within group (order by t.username) as username
WITH temp1 AS(
select 'a' as username,1 as deptid from dual union all
select 'b',1 from dual union all
select 'c',1 from dual union all
select 'd',2 from dual union all
select 'e',2 from dual
),
temp2 AS(
select 1 as deptid,'部门1' as deptname from dual union all
select 2 ,'部门2' from dual
)
select p.deptid,
listagg(t.username,',') within group (order by t.username) as username,
p.deptname
from temp1 t,temp2 p
where t.deptid=p.deptid
group by p.deptid,p.deptname
order by p.deptid
方法三:sys_connect_by_path(column,<分隔符>)
介绍:其函数在Oracle 9i 版本中推出,用来合并链路的字符串。注意的是其一定要和connect by子句合用!第一个参数是形成树形式的字段,第二个参数是父级和其子级分隔显示用的分隔符。