假设我有字符串
Str = 'Aaa,Bbb,Abb,Ccc'
我想将上面的str分为两部分,如下所示
Str1 = 'Aaa,Abb'
Str2 = 'Bbb,Ccc'
这就是以A开头的str中的任何单词都应该在str1中以str1的形式进行休息。
如何使用Oracle查询实现此目的?
答案 0 :(得分:3)
这就是以A开头的str中的任何单词都应该在str1中以str1的形式进行休息。
要在纯 SQL 中实现它,我将使用以下内容:
因此,首先我将使用此处Split single comma delimited string into rows演示的技术拆分逗号分隔的字符串。
然后,我会在订单中使用 LISTAGG 汇总它们。
例如,
SQL> WITH
2 t1 AS (
3 SELECT 'Aaa,Bbb,Abb,Ccc' str FROM dual
4 ),
5 t2 AS (
6 SELECT trim(regexp_substr(str, '[^,]+', 1, LEVEL)) str
7 FROM t1
8 CONNECT BY LEVEL <= regexp_count(str, ',')+1
9 ORDER BY str
10 )
11 SELECT
12 (SELECT listagg(str, ',') WITHIN GROUP(
13 ORDER BY NULL) str1
14 FROM t2
15 WHERE SUBSTR(str, 1, 1)='A'
16 ) str1,
17 (SELECT listagg(str, ',') WITHIN GROUP(
18 ORDER BY NULL) str
19 FROM t2
20 WHERE SUBSTR(str, 1, 1)<>'A'
21 ) str2
22 FROM dual
23 /
STR1 STR2
---------- ----------
Aaa,Abb Bbb,Ccc
SQL>
WITH 子句仅用于演示目的,在您的实际场景中,删除with子句并直接使用您的表名。虽然使用WITH子句看起来很整洁。
答案 1 :(得分:0)
使用regext表达式和ListAg函数。
注意:自Oracle 11g以来,LISTAGG功能可用!
select listagg(s.name, ',') within group (order by name)
from (select regexp_substr('Aaa,Bbb,Abb,Ccc,Add,Ddd','[^,]+', 1, level) name from dual
connect by regexp_substr('Aaa,Bbb,Abb,Ccc,Add,Ddd', '[^,]+', 1, level) is not null) s
group by decode(substr(name,1,1),'A', 1, 0);
答案 2 :(得分:0)
此查询在两个不同的行中为您提供所需的输出:
with temp as (select trim (both ',' from 'Aaa,Bbb,Abb,Ccc') as str from dual),
base_table as
( select trim (regexp_substr (t.str,
'[^' || ',' || ']+',
1,
level))
str
from temp t
connect by instr (str,
',',
1,
level - 1) > 0),
ult_table as
(select str,
case upper (substr (str, 1, 1)) when 'A' then 1 else 2 end
as l
from base_table)
select listagg (case when l = 1 then str else null end, ',')
within group (order by str)
str1,
listagg (case when l = 2 then str else null end, ',')
within group (order by str)
str2
from ult_table;
<强>输出强>
L STR
---------- --------------------------------------------------------------------------------
1 Aaa,Abb
2 Bbb,Ccc