2012-07-04 46 views
1

我在計算如何創建一個顯示子列與其後續父列的所有關係的表時遇到一些麻煩。我在Teradata SQL Assistant中使用SQL。SQL - 從父子列中創建樹

例如,下面是數據我有:

 
Parent | Child        
A  | B              
A  | C   
B  | D   
E  | E 

我希望能夠得到一個輸出表,顯示了其隨後所有的父元素的最低水平子元素如下:

 
Child | ParentL1 | Parent L2   
C  | A  
D  | B  | A  
E 

問題是,我不知道我的數據中存在多少父母級別,而且我只允許訪問查詢數據,所以我無法創建新表格,更改此表格或更改任何值。

有沒有什麼辦法在查詢中獲得預期的輸出?

謝謝!

+1

不Teradata的支持遞歸公用表表達式? ('RECURSIVE ...') –

+0

是的! :) – tremonti92

+0

如何識別層次結構的「開始」或「結束」? –

回答

3

像這樣的東西(在PostgreSQL測試,因爲我沒有的Teradata提供):

with recursive tree as (

    select parent, child, child||'/'||parent as path 
    from foo 
    where child not in (select parent from foo) 
    or parent = child 

    union all 

    select c.parent, c.child, p.path||'/'||c.parent 
    from foo c 
     join tree p on c.child = p.parent 
    where c.parent <> c.child 
) 
select path 
from tree 
order by parent; 
+0

謝謝!我會試一試,讓你知道它是如何發生的! – tremonti92