2016-01-21 40 views
-3

我有一個表的Oracle SQL - 結合兩列到一個

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

現在我要像下面的輸出(從A所有可能的途徑就這樣結束ABCD點,ABCE)

Column 1 
    A 
    B 
    C 
    D 
    A 
    B 
    C 
    E 
+1

所以,你想一個[分層查詢(http://docs.oracle.com/cd/E11882_01/server.112/e41084/queries003.htm)?你怎麼知道從A開始? –

+0

還有另一個查詢告訴我開始點。 是的,我想要一個分層查詢。 就像火車從A站開始,有許多車站。所以列車可以到達終點的所有路線。 –

+1

你的例子不是很清楚。請閱讀http://stackoverflow.com/help/how-to-ask 這裏是[** START **]的好地方(http://spaghettidba.com/2015/04/24/how-to -post-at-sql-question-on-a-public-forum /) –

回答

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; 
0

將somethi這樣做是你的追求?

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