Oracle根据列值将行拆分为多行

时间:2016-12-06 12:35:30

标签: sql oracle

我需要有关如何实现以下目标的建议。

我有一张与此类似的表格:

WITH CTE ( slno, column1, column2, column3, slno2, column4, column5, column6, column7, column8, column9, column10, column11 ) AS (
  SELECT 10000, 'a', 'aa', ';', 10000, 'aaa', 'aaaa', 'aaaaa','aaaaaa', ';', 'aaaaa2', 'aaaaa12', 'aaaa22' FROM DUAL UNION 
  SELECT 10001, 'b', 'bb', ';', 10001, 'bbb', 'bbbb', 'bbbb', 'bbbbbb', ';', 'bbbbb2', 'bbbbb12', 'bbb22'  FROM DUAL UNION 
  SELECT 10001, 'c', 'cc', ';', 10001, 'ccc', 'cccc', 'cccc', 'cccccc', ';', 'ccccc2', 'ccccc12', 'ccc22'  FROM DUAL
)

表格似乎

SLNO    COLUMN1 COLUMN2 COLUMN3 SLNO2   COLUMN4 COLUMN5 COLUMN6 COLUMN7 COLUMN8 COLUMN9 COLUMN10    COLUMN11
10000   a   aa  ;   10000   aaa aaaa    aaaaa   aaaaaa  ;   aaaaa2  aaaaa12 aaaa22
10002   b   bb  ;   10002   bbb bbbb    bbbb    bbbbbb  ;   bbbbb2  bbbbb12 bbb22
10003   c   cc  ;   10003   ccc cccc    cccc    cccccc  ;   ccccc2  ccccc12 ccc22

我需要拆分此表中的每一行,拆分应该发生在第3列和第8列(人工添加;以便有一个分隔符)

最后,输出应该如下:

Column  Column  Column  Column  Column  Column
10000   a   aa  ;       
10000   aaa aaaa    aaaaa   aaaaaa  ;
aaaaa2  aaaaa12 aaaa22          
10001   b   bb  ;       
10001   bbb bbbb    bbbb    bbbbbb  ;
bbbbb2  bbbbb12 bbb22           
10001   c   cc  ;       
10001   ccc cccc    cccc    cccccc  ;
ccccc2  ccccc12 ccc22

添加分号以具有分隔符和应该分割行的标记。 有什么想法吗?

1 个答案:

答案 0 :(得分:0)

select slno c1, column1 c2, column2 c3, ';' c4, null c5, null c6 from table
union all
select column4 c1, column5 c2, column6 c3, column7 c4, column8 c5, ';' c6 from table
union all
select column9 c1, column10 c2, column11 c3, ';' c4, null c5, null c6 from table;

如果您需要此订购,您可以:

select c1, c2, c3, c4, c5, c6 from
(    select slno c1, column1 c2, column2 c3, ';' c4, null c5, null c6, rowid r from table
    union all
    select column4 c1, column5 c2, column6 c3, column7 c4, column8 c5, ';' c6, rowid r from table
    union all
    select column9 c1, column10 c2, column11 c3, ';' c4, null c5, null c6, rowid r from table)
order by r

修改

如果这只是出口我会选择:

select slno  || ',' ||  column1  || ',' || column2  || ',' ||  ';' linerow from table
union all
select column4 || ',' || column5 || ',' || column6  || ',' ||  column7 c4 || ',' ||  column8 c5 || ',' ||  ';' linerow from table
union all
select column9  || ',' ||  column10  || ',' ||  column11  || ',' ||  ';' linerow from table;