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

How to split single rows into multiple rows depending on whether one field contains comma separated string in oracle sql?

我创建了一个函数 get_depatment_names,它在单个 Return 值中用 returns 逗号分隔值。 函数的输出是:Sales,Retail,Electronic。

另一个函数get_location_namesreturns同理定位。输出:西约克、夏尔、兰卡斯

现在,这两个函数,我正在调用我的 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 --- 零售 --- Shire -- 活跃

1--01/01/2018 --- Electronic ---Lancas --Active

我尝试在 select stmt 中使用 regexp_sub 和连接,如下所示,但给出了 "single row subquery returns more than one row".

错误
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;

请告诉我如何更正此问题。

应该是这样的(第 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>