如何在oracle plsql中根据列中逗号分隔的值拆分选择查询行。

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

我写了2个查询Union.I'm得到的结果是逗号分隔的两列。和输出显示为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) "的地方,最后一条记录应该作为一条记录显示,而不是拆分。请告诉我怎么做。

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

sql oracle split comma
1个回答
2
投票

请使用下面的查询。

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);
© www.soinside.com 2019 - 2024. All rights reserved.