方法一:wmsys.wm_concat(column)
介绍:其函数在Oracle 10g推出,在10g版本中,返回字符串类型,在11g版本中返回clob类型。括号里面的参数是列,而且可以是多个列的集合,也就是说在括号里面可以自由地用‘||’合并字符串。如下面的例子:
Select u_id, wmsys.wm_concat(goods ||
'(' || num || '斤)' ) goods_sum
from shopping
group by u_id
方法二:listagg (column,[,]) within group (order by ) [over
(partition by )]
介绍:其函数在Oracle 11g
版本中推出,对分组后的数据按照一定的排序进行字符串连接。其中,“[,]”表示字符串连接的分隔符,如果选择使用[over
(partition by )]则会使其变成分析函数;
方法三:sys_connect_by_path(column,<分隔符>)
介绍:其函数在Oracle 9i 版本中推出,用来合并链路的字符串。注意的是其一定要和connect by子句合用!第一个参数是形成树形式的字段,第二个参数是父级和其子级分隔显示用的分隔符。
下面是上面几种方法的实例(在Oracle
11g版本中运行正确):
实例:
方法一:用listagg(,',') within
group()
SQL
code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
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
-------------------------
deptid userName
deptName
1 a,b,c
部门1
2 d,e
部门2
|
方法二:用wm_concat()
SQL
code
1
2
3
4
5
6
7
8
9
10
|
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
|
方法三:用CONNECT BY
SQL
code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
select deptid,
ltrim(max(sys_connect_by_path(username,',')),','),
deptname
from (
select p.deptid,t.username,p.deptname,
row_number()over(partition by
t.deptid order by t.username) as ar
from temp1 t,temp2
p
where t.deptid=p.deptid
)
start with ar=1
connect by prior ar=ar-1
and username=prior username
group by deptid,deptname
order by deptid
|
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------如有错误,请指教!
--------------技术交流QQ:1732035211
-------------技术交流邮箱:1732035211@qq.com
|