将几个逗号字符串转换为行

时间:2015-06-24 08:24:22

标签: sql string oracle oracle12c regexp-substr

我在这张桌子上(假期):

CCAA     FREEDAYS
AND       01/01,01/03
MAD       01/01,03/03
EUS       01/01,31/12
    ....

我想获得另一张表:

CCAA     FREEDAY
AND       01/01
AND       01/03
MAD       01/01
MAD       03/03
EUS       01/01
EUS       31/12
     ...

我正在使用此SQL查询:

with t as (SELECT freedays AS txt, CCAA AS CCAA
          FROM HOLIDAYS )

select REGEXP_SUBSTR (txt, '[^,]+', 1, level) as freeday, CCAA
from t
connect by REGEXP_SUBSTR (txt, '[^,]+', 1, level) is not null

但是我获得了一张有无穷无尽行的桌子......

你能帮助我吗?非常感谢。

1 个答案:

答案 0 :(得分:1)

您需要connect-by子句链接回相同的CCAA值;但是,由于引入了循环,您还需要包含一个非确定性函数。 (this Oracle Community post)对此过程有一个很好的解释。我使用dbms_random.value,您可以使用sys_guid()

...
connect by REGEXP_SUBSTR (txt, '[^,]+', 1, level) is not null
and prior ccaa = ccaa
and prior dbms_random.value is not null;

不知道为什么你这里有CTE,因为它似乎没有添加任何东西:

select REGEXP_SUBSTR (freedays, '[^,]+', 1, level) as freeday, CCAA
from holidays
connect by REGEXP_SUBSTR (freedays, '[^,]+', 1, level) is not null
and prior ccaa = ccaa
and prior dbms_random.value is not null;

FREEDAY     CCA
----------- ---
01/01       AND
01/03       AND
01/01       EUS
31/12       EUS
01/01       MAD
03/03       MAD

 6 rows selected