sql—如何根据oracle plsql中列中以逗号分隔的值拆分select查询行

gfttwv5a  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(303)

我写了两个查询。我得到的结果用逗号分隔在两列中。输出显示为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

部门名称为“biotech(chemistry,tech)”的最后一条记录应显示为单个记录,不得拆分。请告诉我怎么做。
jim给出的查询工作正常,除非在这个场景中,dept\u name是biotech(chemistry,tech),因为现在给出了需求。

ui7jx7zq

ui7jx7zq1#

请使用下面的查询,

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);

相关问题