首页 > 解决方案 > Oracle 拆分表列分隔值到行

问题描述

需要帮助从测试中选择 col1、col2、split(col3);

表值:

Col1 col2 col3
xxx  yyy  a,b,c
iii  jjj  1,2,3

col3 包含逗号分隔的值。

希望达到以下结果。为相同的 col1 和 col2 值拆分 Col3 值。

col1 col2 split
xxx  yyy  a
xxx  yyy  b
xxx  yyy  c
iii  jjj  1
iii  jjj  2
iii  jjj  3

任何正则表达式或 pl/sql 函数的想法都可以帮助解决这个问题。

标签: sqlstringoraclecsvrecursive-query

解决方案


一种选择使用标准递归查询:

with cte (col1, col2, pos, split, rest) as (
    select col1, col2, 1,
        substr(col3 || ',', 1, instr(col3 || ',', ',') - 1), 
        substr(col3 || ',', instr(col3 || ',', ',') + 1)
    from mytable 
    union all
    select col1, col2, pos + 1,
        substr(rest, 1, instr(rest, ',') - 1),
        substr(rest, instr(rest, ',') + 1)
    from cte 
    where instr(rest, ',') > 0
)
select col1, col2, split, pos from cte order by col1, col2, pos

DB Fiddlde 上的演示

COL1 | COL2 | 分裂 | POS
:--- | :--- | :---- | --:
iii | jjj | 1 | 1
iii | jjj | 2 | 2
iii | jjj | 3 | 3
xxx | 年年 | 一个 | 1
xxx | 年年 | 乙 | 2
xxx | 年年 | c | 3

推荐阅读