0

我有一些桌子

1 | 2 | 测试,测试| 4

我需要一个查询以这种格式返回此表:

1 | 2 | 测试 | 4
1 | 2 | 测试 | 4
4

2 回答 2

0

很抱歉给你链接。但是,可能会对你有所帮助。

http://www.dba-oracle.com/t_converting_rows_columns.htm

http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:419593546543

于 2013-09-23T10:57:53.347 回答
0
with src as
(
        select  '1' col0,  '2' col1, 'test1,test2'   col2 from dual union all
        select '11' col0, '22' col1, 'test11,test22' col2 from dual
)
, explode as
(
        select  col0
        ,       col1
        ,       regexp_substr(col2, '\w+', 1, 1) as col2_1
        ,       regexp_substr(col2, '\w+', 1, 2) as col2_2
        --      if there is more add more...
        from    src
)
select col0, col1, col2_1 from explode where col2_1 is not null union all
select col0, col1, col2_2 from explode where col2_2 is not null 
order by col0, col1, col2_1
;

1   2   test1
1   2   test2
11  22  test11
11  22  test22

五个值的示例:

with src as
(
        select  '1'  col0,   '2' col1, 'test1,test2'                        col2 from dual union all
        select '11'  col0,  '22' col1, 'test11,test22'                      col2 from dual union all
        select '111' col0, '222' col1, 'test31,test32,test33,test34,test35' col2 from dual
)
, explode as
(
        select  col0
        ,       col1
        ,       regexp_substr(col2, '\w+', 1, 1) as col2_1
        ,       regexp_substr(col2, '\w+', 1, 2) as col2_2
        ,       regexp_substr(col2, '\w+', 1, 3) as col2_3
        ,       regexp_substr(col2, '\w+', 1, 4) as col2_4
        ,       regexp_substr(col2, '\w+', 1, 5) as col2_5
        --      if there is more add more...
        from    src
)
select col0, col1, col2_1, col2_2, col2_3, col2_4, col2_5 from explode where col2_1 is not null union all
select col0, col1, col2_1, col2_2, col2_3, col2_4, col2_5 from explode where col2_2 is not null union all
select col0, col1, col2_1, col2_2, col2_3, col2_4, col2_5 from explode where col2_3 is not null union all
select col0, col1, col2_1, col2_2, col2_3, col2_4, col2_5 from explode where col2_4 is not null union all
select col0, col1, col2_1, col2_2, col2_3, col2_4, col2_5 from explode where col2_5 is not null
order by col0, col1, col2_1, col2_2, col2_3, col2_4, col2_4, col2_5
;

1   2   test1   test2           
1   2   test1   test2           
11  22  test11  test22          
11  22  test11  test22          
111 222 test31  test32  test33  test34  test35
111 222 test31  test32  test33  test34  test35
111 222 test31  test32  test33  test34  test35
111 222 test31  test32  test33  test34  test35
111 222 test31  test32  test33  test34  test35
于 2013-09-23T10:59:07.777 回答