Oracle中SYS_CONNECT_BY_PATH函数的妙用 ;

Oracle 中SYS_CONNECT_BY_PATH函数是非常重要的函数,下面就为您介绍一个使用SYS_CONNECT_BY_PATH函数的例子,实例如下:

数据准备:

1 create table test (a varchar2(10),b varchar2(10));  
2  
3 INSERT INTO TEST (A, B) VALUES ('1', 'A');  
4 INSERT INTO TEST (A, B) VALUES ('1', 'B');  
5 INSERT INTO TEST (A, B) VALUES ('2', 'X');  
6 INSERT INTO TEST (A, B) VALUES ('2', 'Y');  
7 
8 SELECT A, B FROM TEST  ;

 

 

1 SELECT A, LTRIM(MAX(SYS_CONNECT_BY_PATH(B, ' ')), ',') B
2   FROM (SELECT B, A, ROW_NUMBER() OVER(PARTITION BY A ORDER BY B DESC) RN
3           FROM TEST)
4  START WITH RN = 1
5 CONNECT BY RN - 1 = PRIOR RN
6        AND A = PRIOR A
7  GROUP BY A;

 

------------------------------------------

将 'A,B,C,D,E,F,G'拆分成行显示 ;

 1 /*
 2 1.分析先找出有多少个‘,’逗号:length(str) - length(regexp_replace(str, ',', '')) + 1 ;
 3 2.再根据regexp_substr()函数进行查找逗号的位置 ;
 4  regexp_substr(str, '[^,]+', 1, level, 'i') as str ,这里的level代表第几个逗号(‘,’)
 5 
 6 3.function REGEXP_SUBSTR(__srcstr, __pattern, __position, __occurrence, __modifier) ;
 7            参数的含义:
 8            __srcstr     :需要进行正则处理的字符串
 9            __pattern    :进行匹配的正则表达式
10            __position   :起始位置,从第几个字符开始正则表达式匹配(默认为1)
11            __occurrence :标识第几个匹配组,默认为1
12            __modifier   :模式('i'不区分大小写进行检索;'c'区分大小写进行检索。默认为'c'。)
13 */
14 
15 with temp as
16  (select 'A,B,C,D,E,F,G' str from dual)
17 select regexp_substr(str, '[^,]+', 1, level, 'i') as str
18   from temp
19 connect by level <= length(str) - length(regexp_replace(str, ',', '')) + 1;

1 A,B,C,D,E,F,G' 
 
1 A
1 B
1 C
1 D
1 E
1 F

 

posted @ 2017-12-29 11:42  linbo.yang  阅读(5640)  评论(0编辑  收藏  举报