【发布时间】:2020-12-02 15:08:00
【问题描述】:
我想从表中的一行创建一行,其中包含某些字段的分隔符,如下面的屏幕截图所示
我想要一个结果 A separalte rows 已经包含分隔符 ; 的行
输入是表 1 中的数据,输出是使用 oracle sql 的表 2 中提到的数据:插入和选择查询
您可以在下面看到推荐的输出:
【问题讨论】:
我想从表中的一行创建一行,其中包含某些字段的分隔符,如下面的屏幕截图所示
我想要一个结果 A separalte rows 已经包含分隔符 ; 的行
输入是表 1 中的数据,输出是使用 oracle sql 的表 2 中提到的数据:插入和选择查询
您可以在下面看到推荐的输出:
【问题讨论】:
一种方法是递归 CTE:
with cte(id, description, val, before, after, n, cnt) as (
select id, description, val, before, after, 1 as n, regexp_count(description, ';')
from t
union all
select id, description, val, before, after, n + 1, cnt
from cte
where n <= cnt
)
select id,
regexp_substr(description, '[^;]+', 1, n) as description,
regexp_substr(val, '[^;]+', 1, n) as val,
regexp_substr(before, '[^;]+', 1, n) as before,
regexp_substr(after, '[^;]+', 1, n) as after
from cte;
Here 是一个 dbfiddle。
【讨论】:
或者:
SQL> with test (id, description, val, after, before) as
2 -- you already have sample data and don't type this
3 (select 1, 'ARTIC1;ARTIC2;ART11', '15;2;3', '12;6;8', '13;7;12' from dual union all
4 select 2, 'ARTICLE3;ARTICLE4' , '3;5' , '10;23' , '12;25' from dual union all
5 select 3, 'ARTICLE 5' , '6' , '2' , '1.9' from dual
6 )
7 -- query that does the job begins here
8 select id,
9 regexp_substr(description, '[^;]+', 1, column_value) descr,
10 regexp_substr(val , '[^;]+', 1, column_value) val,
11 regexp_substr(after , '[^;]+', 1, column_value) after,
12 regexp_substr(before , '[^;]+', 1, column_value) before
13 from test cross join
14 table(cast(multiset(select level from dual
15 connect by level <= regexp_count(description, ';') + 1
16 ) as sys.odcinumberlist))
17 order by id, descr, val;
ID DESCR VAL AFTER BEFORE
---------- ---------- ---------- ---------- ----------
1 ARTIC1 15 12 13
1 ARTIC2 2 6 7
1 ART11 3 8 12
2 ARTICLE3 3 10 12
2 ARTICLE4 5 23 25
3 ARTICLE 5 6 2 1.9
6 rows selected.
SQL>
【讨论】: