問題:oracle LISTAGG 連接字符串;結果:Oracle 連接字符串的方法


Oracle 連接字符串的方法


方法一: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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM