sql - 递归 CTE 未获得预期结果。如何仅分配 anchor ?

标签 sql sql-server tsql recursion common-table-expression

申请是一个员工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/

相关文章:

sql - 需要帮助限制 Transact-sql 中的联接

sql - 通过聚合连接一个表本身

Mysql SQL更新没有www的网址

mysql - 在 MySQL Server 中创建一个以一对作为主键的表

php - 将 datetime 转换为 varchar 从 MSSQL 到 MYSQL

sql - 使用查询访问 SQL 中的列描述

mysql - 无法对特定记录运行查询

java - 使用 HSQLDB 测试日期值

sql-server - SQL Server 中的超大表

sql - T-SQL XQuery 用于为每个嵌套元素的每个匹配的 XML 值返回一个结果行