如何根据Oracle sql中的一个字段是否包含逗号分隔的字符串将单行拆分为多行?

问题描述 投票:0回答:1

我已经创建了一个函数get_depatment_names,该函数在单个“返回值”中返回逗号分隔的值。功能的输出为:销售,零售,电子。

另一个功能get_location_names返回相同的位置信息。输出:西约克,夏尔,兰卡斯

现在,这两个函数是我在select语句中与其他列一起调用的。

SELECT dept_id,
       date,
       get_department_names dept_name,
       get_location_names location
       status
FROM   department
WHERE dept_id = 1;

输出显示如下

dept_id ---日期---- dept_name -------位置-----状态

1 --- 01/01/2018 ---销售,零售,电子---西约克,夏尔,兰卡斯-有效

预期输出:

1--01 / 01/2018 ---销售---西约克-有效

1--01 / 01/2018 ---零售---郡-活跃

1--01 / 01/2018 ---电子--- Lancas-正在使用

我尝试如下将regexp_sub与select stmt中的connect一起使用,但出现错误“单行子查询返回多个行”。

SELECT dept_id,
       date,
       (select regexp_substr(get_department_names(id),'[^,]+',1,level) from dual
        connect by regexp_substr(get_department_names(id),'[^,]+',1,level) is not null)  dept_name,
       (select regexp_substr(get_location_names (id),'[^,]+',1,level) from dual
        connect by regexp_substr(get_location_names(id),'[^,]+',1,level) is not null) location
       status
FROM   department
WHERE dept_id = 1;

请让我知道如何纠正此问题。

oracle split comma delimiter-separated-values
1个回答
0
投票

将是这样(第1-4行代表示例数据;您需要的查询从第5行开始):

SQL> with department (dept_id, datum, dept_name, location, status) as
  2    (select 1, date '2018-01-01', 'sales,retail,electronic',
  3      'West York,Shire,Lancas', 'active' from dual
  4    )
  5  select dept_id,
  6    datum,
  7    regexp_substr(dept_name, '[^,]+', 1, level) dept_name,
  8    regexp_substr(location , '[^,]+', 1, level) location,
  9    status
 10  from department
 11  where dept_id = 1
 12  connect by level <= regexp_count(dept_name, ',') + 1;

   DEPT_ID DATUM      DEPT_NAME       LOCATION        STATUS
---------- ---------- --------------- --------------- ------
         1 01/01/2018 sales           West York       active
         1 01/01/2018 retail          Shire           active
         1 01/01/2018 electronic      Lancas          active

SQL>
© www.soinside.com 2019 - 2024. All rights reserved.