2012-04-24 83 views
0

我有一個數據返回使用遞歸CTE的所有非葉子節點MS SQL

id  name  mgtId 
-------------------------- 
1  joe   null 
2  jack   1 
3  jill   1 
4  paul   2 
5  ron   4 
6  sam   2 

mgtId引用編號的表。我如何使用CTE選擇非葉節點(joe,jack,paul)。

+0

爲什麼你想/需要遞歸解決方案? – 2012-04-24 22:38:26

回答

1
select * 
from table 
where id in (select mgtId from table) 
+0

不需要,我想... – therealmitchconnors 2012-04-24 21:11:42

+0

它不選擇根節點 – Naveen 2012-04-24 21:23:09

+0

這個查詢將選擇喬,傑克和保羅,就像你所要求的。 – therealmitchconnors 2012-04-24 21:28:25

1

方式一:

;with parents_id as (
    select distinct mgtId as id 
    from your_table 
) 
select * 
from your_table t 
inner join parants_id p on t.id = p.id 

修訂 25 APRL 2012

我來test above query和它的工作原理,並返回根節點:

select * 
into #your_table 
from (
select 1 as id, 'joe' as name, null as mgtId union all 
select 2,  'jack ',  1 union all 
select 3,  'jill ' ,  1 union all 
select 4,  'paul ' ,  2 union all 
select 5,  'ron ' ,  4 union all 
select 6,  'sam' ,  2 ) T 


;with parents_id as (
    select distinct mgtId as id 
    from #your_table 
) 
select * 
from #your_table t 
inner join parents_id p on t.id = p.id 

結果:

id name mgtId id 
-- ------- ----- -- 
1 joe  null 1 
2 jack 1  2 
4 paul 2  4 
+0

它不選擇根節點(joe)。 – Naveen 2012-04-24 21:21:26

+0

你確定嗎?我已經檢查了兩個和根節點是否包含在結果中,請參閱更新的評論。 – danihp 2012-04-25 07:34:21

+0

對不起,您的解決方案確實有效。順便提一下,我構建了一個錯誤的例子,該表可能包含一些未鏈接的節點,這些節點也應該被選中 – Naveen 2012-04-25 16:10:29

0

與CTE爲( 選擇ID,從mgtId mgr_emp ) 選擇b.id,b.name,b.mgtId,a.mgtId從CTE右連接mgr_emp b 上b.mgtId =一.id