逗号分隔的字符串列表

时间:2017-02-14 12:29:52

标签: sql oracle

我有一个字符串,其值如下:

Countries = USA, Canada, Italy

我想将它们分开并将其显示为如下所示的列表

Countries
USA
Canada
Italy

如何使用SQL执行此操作?

2 个答案:

答案 0 :(得分:1)

Oracle文档页面的Splitting Delimited Strings主题中发布了多个解决方案。

一个是:

示例数据

CREATE TABLE table_name ( id, list ) AS
SELECT 1, 'a,b,c,d' FROM DUAL UNION ALL -- Multiple items in the list
SELECT 2, 'e'       FROM DUAL UNION ALL -- Single item in the list
SELECT 3, NULL      FROM DUAL UNION ALL -- NULL list
SELECT 4, 'f,,g'    FROM DUAL;          -- NULL item in the list

<强>查询

SELECT t.id,
       v.COLUMN_VALUE AS value,
       ROW_NUMBER() OVER ( PARTITION BY id ORDER BY ROWNUM ) AS lvl
FROM   table_name t,
       TABLE(
         CAST(
           MULTISET(
             SELECT REGEXP_SUBSTR( t.list, '([^,]*)(,|$)', 1, LEVEL, NULL, 1 )
             FROM   DUAL
             CONNECT BY LEVEL < REGEXP_COUNT( t.list, '[^,]*(,|$)' )
           )
           AS SYS.ODCIVARCHAR2LIST
         )
       ) v;

<强>输出

        ID ITEM           LVL
---------- ------- ----------
         1 a                1 
         1 b                2 
         1 c                3 
         1 d                4 
         2 e                1 
         3 (NULL)           1 
         4 f                1 
         4 (NULL)           2 
         4 g                3 

答案 1 :(得分:0)

您可以使用regex_substr和连接

  select regexp_substr( 'USA, Canada, Italy','[^,]+', 1, level) from dual
  connect by regexp_substr('USA, Canada, Italy', '[^,]+', 1, level) is not null;