获取空格和所有组合之前和之后的子字符串

时间:2017-01-09 16:32:26

标签: sql oracle oracle10g

我得到了一个名为'sentence'的唯一列的表

Create Table Test(
sentence VARCHAR2(100);
);

Insert into Test('this is a message');

基本上我想要实现的是获取空格之后和之前的所有子字符串。但是,我执行的查询只占用空格

之前的子字符串
SELECT (Regexp_substr (sentence, '^[^ ]+ ')) sentence_new 
FROM Test
GROUP BY sentence; 

我想要的结果是

RESULT
---------------------
This
is
a
test
This is
This a
This test
is test
is this
is a
a This
a is
a test
Test this
test a
test is
This is a 
This is test
This a test
a is this
a test this
a this is
is this a
is test a
is this test
test a this
test is this
test this is

1 个答案:

答案 0 :(得分:0)

问题分为两部分。

第一部分是创建一个视图(查询结果),它将包含四个单词,每个空格分隔。你已经能够做到这一点。 编辑:实际上,在重新阅读时,你不是。见下文(本答复的底部)。

第二部分是获得所有"组合" 1,2,3或4个不同字,由空格分隔。对于数学正确性,您可能还应该将空字符串包含为0个单词的组合,但这可以单独解决。

一种方法是使用分层查询。这是一个例子,它将产生来自集合{1,2,3,4}的1,2,3或4个不同值的所有组合。注意结果也会有一个领先的空间;您可以使用ltrim()将其删除。我没有显示输出,因为它是64行,但您可以在数据库上运行它。

with
     inputs ( n ) as (
       select 1 from dual union all
       select 2 from dual union all
       select 3 from dual union all
       select 4 from dual
     )
--  end of test data; SQL query begins below this line
select sys_connect_by_path(n, ' ') as result
from   inputs
connect by nocycle prior n > 0
;

根据您的练习进行调整 - 而不是inputs您应该从第一个查询的结果中选择(将句子拆分为单个单词),而不是n您应该使用该列您在那里创建的别名(sentence_new)。

修改 - 我重新阅读了您的帖子,发现您无法将该句子拆分为所有组成单词。这是通过另一个分层查询完成的。这有多复杂取决于输入中只有一行,还是很多。如果您只有一行,那就很简单:

SELECT (Regexp_substr (sentence, '[^ ]+ ', 1, level)) sentence_new 
FROM Test
connect by level <= 1 + regexp_count(sentence, ' +')
相关问题