首页 > 解决方案 > 如何根据oracle plsql中列中的逗号分隔值拆分选择查询行

问题描述

我写了2个查询Union。我得到的结果以逗号分隔在两列中。输出显示为 2 条记录。

如何将它们拆分为 4 条记录,如下预期结果?

select emp_id,dept_name,location from department where dept_id = 1
union
select emp_id,dept_name,location from sales_dept where dept_id = 1;

输出

emp_id ----- dept_name------  location

r1-----------Retail,IT-----   US, UK
k2-----------Sales,Chemical-  NZ, SA
j3-----------Biotech(Chemistry,Tech)-   JA

我需要如下的预期输出

emp_id ----- dept_name-----location
r1-----------Retail--------US
r1-----------IT----------- UK
k2-----------Sales---------NZ
k2-----------Chemical------SA
j3---------Biotech(Chemistry,Tech)--JA

dept_name 为“Biotech(Chemistry,Tech)”的最后一条记录应显示为单个记录,不得拆分。请让我知道该怎么做。

Jim 给出的查询工作正常,但在这种情况下,dept_name 是 Biotech(Chemistry,Tech),因为现在给出了要求。

标签: sqloraclesplitcomma

解决方案


请使用以下查询,

select emp_id, dept_name, location from
(select distinct emp_id, trim(regexp_substr(dept_name,'[^,]+', 1, level) ) dept_name, 
trim(regexp_substr(location,'[^,]+', 1, level) ) location, level
from pivot_comma
connect by regexp_substr(dept_name, '[^,]+', 1, level) is not null 
order by emp_id, level);

推荐阅读