Oracle由regex拆分并再次聚合

时间:2013-10-23 11:48:48

标签: sql oracle oracle10g

我有一个table,我需要在记录的一部分之后才能获得记录的某些部分 with comma

for example我有

ABCD [1000-1987] BCD[101928-876] adgs[10987-786]

我想得到record之类的:

1000-1987,101928-876,10987-786

请你帮我解决上面提到的记录。

2 个答案:

答案 0 :(得分:4)

如果您不使用11g且不想使用wm_concat

WITH
  my_data AS (
    SELECT 'ABCD [1000-1987] BCD[101928-876] adgs[10987-786]' AS val FROM dual
)
SELECT
    ltrim(
      MAX(
        sys_connect_by_path(
          rtrim(ltrim(regexp_substr(val, '\[[0-9-]*\]', 1, level, NULL), '['), ']'),
          ',')
      ),
    ',') AS val_part
  FROM my_data
CONNECT BY regexp_substr(val, '\[[0-9-]*\]', 1, level, NULL) IS NOT NULL
;

如果您可以使用wm_concat

WITH
  my_data AS (
    SELECT 'ABCD [1000-1987] BCD[101928-876] adgs[10987-786]' AS val FROM dual
)
SELECT
    wm_concat(rtrim(ltrim(regexp_substr(val, '\[[0-9-]*\]', 1, level, NULL), '['), ']')) AS val_part
  FROM my_data
CONNECT BY regexp_substr(val, '\[[0-9-]*\]', 1, level, NULL) IS NOT NULL
;

如果您使用11g:

WITH
  my_data AS (
    SELECT 'ABCD [1000-1987] BCD[101928-876] adgs[10987-786]' AS val FROM dual
)
SELECT
    listagg(regexp_substr(val, '[a-b ]*\[([0-9-]*)\] ?', 1, level, 'i', 1), ',') WITHIN GROUP (ORDER BY 1) AS val_part
  FROM my_data
CONNECT BY regexp_substr(val, '[a-b ]*\[([0-9-]*)\] ?', 1, level, 'i', 1) IS NOT NULL
;

阅读有关字符串聚合技术的更多信息:Tim Hall about aggregation techniques

详细了解regexp_substrregexp_substr - Oracle Documentation - 10g

详细了解regexp_substrregexp_substr - Oracle Documentation - 11g

答案 1 :(得分:2)

您不必拆分然后聚合它。您可以使用regexp_replace仅将这些字符保留在方括号内,然后用逗号替换方括号。

WITH my_data
     AS (SELECT 'ABCD [1000-1987] BCD[101928-876] adgs[10987-786]' AS val
           FROM DUAL)
SELECT RTRIM (
          REPLACE (
              REGEXP_REPLACE (val, '(\[)(.*?\])|(.)', '\2'),
                  ']', ','),
          ',')
  FROM my_data;