在Oracle DB中拆分字符串

时间:2014-12-22 08:34:44

标签: sql oracle split

我的表中有3行示例:

|-Id-||--props--|
1        aa = black
2        aa = change
         d = eexplore
3        xxx = yield
         d = int
         mmmm = no

我想用结果编写SQL语句:

aa    
d
xxx
mmm

即。输出成对的所有第一个元素x = y。给定表格每行中的对可以用newline分隔。

我已尝试过以下SQL,但结果并不正确

    SELECT REGEXP_SUBSTR ('a = b, b = c',
                          '[^=]',
                          1,
                          LEVEL) as name
      FROM DUAL
CONNECT BY LEVEL <= (SELECT REGEXP_COUNT ('a = b, b = c', '=') FROM DUAL)

2 个答案:

答案 0 :(得分:1)

请尝试以下,sql fiddle here

with names as ( SELECT REGEXP_SUBSTR (regexp_replace('aa = b, bb = c , eee = d','[[:space:]]*',''), '[^=]+', 1, level ) as name FROM DUAL CONNECT BY LEVEL <= (SELECT REGEXP_COUNT ('a = b, b = c , e = d ', '=') FROM DUAL)) select nvl(regexp_substr(name,'[^,]+',1,2),regexp_substr(name,'[^,]+',1,1) ) from names;

Update1:​​ - 您可以用逗号替换新行

在Unix上,LINEFEED(chr(10))是“行尾”标记。 在窗口上CARRIAGE RETURN / LINEFEED(chr(13)|| chr(10))应该是行标记的结尾

with names as
(
 SELECT REGEXP_SUBSTR (regexp_replace(replace('aa = black' ||chr(13)||chr(10)||'bb = change'||chr(13)||chr(10)||'mmmm=no',chr(13)||chr(10),','),'[[:space:]]*',''),
                          '[^=]+',
                          1,
                         level ) as name
      FROM DUAL
CONNECT BY LEVEL <= (SELECT REGEXP_COUNT 
('aa = black' ||chr(13)||chr(10)||'bb = change'||chr(13)||chr(10)||'mmmm=no', '=')
 FROM DUAL)

)
select nvl(regexp_substr(name,'[^,]+',1,2),
regexp_substr(name,'[^,]+',1) ) from names;

答案 1 :(得分:0)

使用substr返回第一个字符:

select substr(LEVEL, 1, 1) from tablename group by substr(LEVEL, 1, 1)