0

我有一张数据表

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)。

4

3 回答 3

1
select *
from table
where id in (select mgtId from table)
于 2012-04-24T21:11:18.140 回答
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 日更新

我来测试上面的查询,它可以工作并且还返回根节点:

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  
于 2012-04-24T21:12:53.127 回答
0

与 cte as( select id,mgtId from mgr_emp ) select b.id,b.name ,b.mgtId ,a.mgtId from cte a right join mgr_emp b on b.mgtId =a.id

于 2012-04-25T05:10:27.737 回答