sql - 如何根据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),因为现在给出了要求。
解决方案
请使用以下查询,
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);
推荐阅读
- android - 无法实例化一个或多个类:Navigation Drawer 和 Render Prob
- php - AWS 使用 StsClient 限制对临时凭证 getSessionToken 的访问
- asp.net-web-api - 看不到为什么带有 2 个日期参数的控制器方法不起作用
- javascript - 为什么结果未定义?
- php - Php mail - 包含数组和条件的消息变量
- php - IGNORE x LINE 进入 INFILE 命令不适用于 x >1
- php - 在数字前使用 {%2B) 而不是 (+) 有什么区别?
- sql-server - 将超过 1M 行加载到 PrimeNG 表
- python - Python/Django with Stripe:创建条带订阅时发布请求出错
- jquery - Toastr 没有出现在 laravel 5.4 中