Oracle to select 通过正则表达式将所有匹配的事件匹配到一行中的一列,并带有分隔符
Oracle to select all matched occurrences by a regular expression to one column in one row with separator
我知道 select 通过正则表达式将所有匹配项匹配到多行中的一列,如下所示:
SELECT REGEXP_SUBSTR(str, '\+?\d{3,11}', 1, LEVEL) AS substr
FROM (
SELECT 'Txa233141b Ta233141 Ta233142 Ta233147 Ta233148' AS str FROM DUAL
)
CONNECT BY LEVEL <= LENGTH(REGEXP_REPLACE(str, '[^ ]+')) + 1;
结果是
233141
233141
233142
233147
233148
但是我想要如下结果,我该怎么办?
233141,233141,233142,233147,233148
您还可以在查询之上使用 listagg,如下所示:
SELECT listagg(REGEXP_SUBSTR(str, '\+?\d{3,11}', 1, LEVEL),',') within group (order by 1) AS substr
FROM (
SELECT 'Txa233141b Ta233141 Ta233142 Ta233147 Ta233148' AS str FROM DUAL
)
CONNECT BY LEVEL <= LENGTH(REGEXP_REPLACE(str, '[^ ]+')) + 1;
干杯!!
使用简单的字符串函数,而不是尝试拆分字符串和聚合它:
查询:
WITH test_data ( str ) AS (
SELECT 'Txa233141b Ta233141 Ta233142 Ta233147 Ta233148' AS str FROM DUAL
)
SELECT TRIM(
TRAILING ',' FROM
REGEXP_REPLACE(
str,
'.*?(\+?\d{3,11}|$)',
','
)
) AS replaced_str
FROM test_data
输出:
| REPLACED_STR |
| :--------------------------------- |
| 233141,233141,233142,233147,233148 |
db<>fiddle here
我知道 select 通过正则表达式将所有匹配项匹配到多行中的一列,如下所示:
SELECT REGEXP_SUBSTR(str, '\+?\d{3,11}', 1, LEVEL) AS substr
FROM (
SELECT 'Txa233141b Ta233141 Ta233142 Ta233147 Ta233148' AS str FROM DUAL
)
CONNECT BY LEVEL <= LENGTH(REGEXP_REPLACE(str, '[^ ]+')) + 1;
结果是
233141
233141
233142
233147
233148
但是我想要如下结果,我该怎么办?
233141,233141,233142,233147,233148
您还可以在查询之上使用 listagg,如下所示:
SELECT listagg(REGEXP_SUBSTR(str, '\+?\d{3,11}', 1, LEVEL),',') within group (order by 1) AS substr
FROM (
SELECT 'Txa233141b Ta233141 Ta233142 Ta233147 Ta233148' AS str FROM DUAL
)
CONNECT BY LEVEL <= LENGTH(REGEXP_REPLACE(str, '[^ ]+')) + 1;
干杯!!
使用简单的字符串函数,而不是尝试拆分字符串和聚合它:
查询:
WITH test_data ( str ) AS (
SELECT 'Txa233141b Ta233141 Ta233142 Ta233147 Ta233148' AS str FROM DUAL
)
SELECT TRIM(
TRAILING ',' FROM
REGEXP_REPLACE(
str,
'.*?(\+?\d{3,11}|$)',
','
)
) AS replaced_str
FROM test_data
输出:
| REPLACED_STR | | :--------------------------------- | | 233141,233141,233142,233147,233148 |
db<>fiddle here