2017-05-29 69 views
0

我有一個像這樣的分層表,它是查詢的結果。在分層表中查找每個組的頂層根組ID SQL

ID Parent Name 
1 35   Alex 
2 50   John 
3 1   Don 
4 3   Anietta 
5 2   Merin 
6 1   Johan 
7 4   Tom 
8 25   Philp 
9 8   Mathew 
-------------------------------- 

這實際上是從一個表

那麼,如何可以選擇從上面的結果通過CTE

頂部根節點過濾行

所以最後的結果是這樣的

ID Parent Name 
------------------------ 
1  35  Alex 
2  50  John 
8  25  Philip 
------------------------- 

從結果中可以清楚地看出,他們是其他成員中最頂級的根,但他們的父母也不在列表中。那麼我怎麼能做到這一點?

回答

0

你可以試試這個僞代碼。

with data as (
    select 1 ID, 35 Parent,'Alex' as name 

union select 2 ID, 50 Parent,   'John' as name 
union select 3 ID, 1 Parent,  'Don' as name 

union select 4 ID , 3 Parent,  'Anietta' as name 
union select 5 ID, 2 Parent,  'Merin' as name 
union select 6 ID, 1 Parent,  'Johan' as name 
union select 7 ID ,4 Parent,  'Tom' as name 
union select 8 ID ,25 Parent,  'Philp' as name 
union select 9 ID ,8 Parent,  'Mathew' as name 
) 
select * from data d1 
where not exists (select 1 from data d2 where d2.id = d1.parent) 
+0

它工作與否? –