我有一张数据表
id name mgtId
--------------------------
1 joe null
2 jack 1
3 jill 1
4 paul 2
5 ron 4
6 sam 2
mgtId引用id。如何使用CTE选择非叶节点(joe,jack,paul)。
答案 0 :(得分:1)
select *
from table
where id in (select mgtId from table)
答案 1 :(得分: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
更新 2012年4月25日
我来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
答案 2 :(得分:0)
以cte为( 从mgr_emp中选择id,mgtId ) 从cte a select join mgr_emp b中选择b.id,b.name,b.mgtId,a.mgtId 在b.mgtId = a.id