Oracle SQL - 将两列合并为一列

时间:2016-01-21 16:17:14

标签: sql oracle select unpivot

我有一张桌子

Column 1       Column 2
   A              B
   B              C
   C              D
   C              E

现在我想要输出如下(从A到终点的所有可能路线,如A-B-C-D,A-B-C-E)

Column 1 
   A
   B
   C
   D
   A
   B
   C
   E

2 个答案:

答案 0 :(得分:0)

您需要记录通过节点的路径,并且只返回完整路径,因此以下内容可以帮助您:

with dat as (
select 'A' col1, 'B' col2 from dual union all
select 'B' col1, 'C' col2 from dual union all
select 'C' col1, 'D' col2 from dual union all
select 'C' col1, 'E' col2 from dual )
select ltrim(the_path,'-')||'-'||col2
from (
    select SYS_CONNECT_BY_PATH(col1, '-') the_path
          ,CONNECT_BY_ISLEAF is_leaf
          ,col2
    from dat
    start with col1 = 'A'
    connect by prior col2 = col1
    ) where is_leaf = 1;

答案 1 :(得分:0)

这样的事情会是你之后的事吗?

with sample_data as (select 'A' col1, 'B' col2 from dual union all
                     select 'B' col1, 'C' col2 from dual union all
                     select 'C' col1, 'D' col2 from dual union all
                     select 'C' col1, 'E' col2 from dual union all
                     select 'A' col1, 'F' col2 from dual)
select connect_by_root(col1)||sys_connect_by_path(col2, '-') route
from   sample_data
where  connect_by_isleaf = 1
connect by prior col2 = col1
start with col1 = 'A';

ROUTE
---------
A-B-C-D
A-B-C-E
A-F