简体   繁体   中英

Oracle split rows into multiple rows based on column value

I need an advice on how to achieve the following.

I have a table similar to this one :

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
)

table looks like

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

I need to split each and every row in this table and the split should happen on columns 3 and 8( the ; is added artificially to have a separator)

Finally, the output should looks like:

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

The semicolons are added to have a separator and a mark where the row should be split. Any ideas?

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;

If you need this ordered you can have:

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

EDIT

If this is just for export I would go for:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM