申请是一个员工id获取所有经理
declare @emp table (id int primary key, mgr int);
insert into @emp values
(1, null)
, (2, 1)
, (3, 2)
, (4, null)
, (5, 4);
select * from @emp;
; with cte as
( select e.id, e.mgr, cnt = 1
from @emp e
union all
select e.id, e.mgr, cnt + 1
from @emp e
join cte
on cte.mgr = e.id
)
select id, mgr, cnt
from cte
where id = 3;
以上仅返回 id = 3 的单行。我知道这是预期的,但不是我想要的。我想在 3 点开始(锚定)并获得经理链。
如果我对 anchor 进行硬编码,我会得到想要的结果。
见下文:
; with cte as
( select e.id, e.mgr, cnt = 1
from @emp e
where e.id = 3
union all
select e.id, e.mgr, cnt + 1
from @emp e
join cte
on cte.mgr = e.id
)
select id, mgr, cnt
from cte;
我的问题是如何仅在 cte 的 where
中分配 anchor (顶部)?
如果不在 where
中,是否有另一种方法仅分配 anchor (而不是在 cte 中进行硬编码)?
最佳答案
你需要在你的cte中保持起始位置:
declare @emp table (id int primary key, mgr int);
insert into @emp values
(1, null)
, (2, 1)
, (3, 2)
, (4, null)
, (5, 4);
; with cte as
( select e.id ori, e.id, e.mgr, cnt = 1
from @emp e
union all
select cte.ori, e.id, e.mgr, cnt + 1
from @emp e
join cte
on cte.mgr = e.id
)
select ori, id, mgr, cnt
from cte
where cte.ori = 3;
结果:
+-----+----+------+-----+
| ori | id | mgr | cnt |
+-----+----+------+-----+
| 3 | 3 | 2 | 1 |
| 3 | 2 | 1 | 2 |
| 3 | 1 | NULL | 3 |
+-----+----+------+-----+
关于sql - 递归 CTE 未获得预期结果。如何仅分配 anchor ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48785358/