【问题标题】:Recursive CTE in SQL [closed]SQL中的递归CTE
【发布时间】:2014-11-15 14:46:56
【问题描述】:

Union all 函数在递归 CTE 中不起作用...?

with CTE_Manager(id,manager,man_id,[Level])
as
(
    select id,manager,man_id,1
    from manager
    where man_id is null

union all

    select a.id,a.manager,a.man_id,b.[Level]+1
    from manager a
    join CTE_Manager b
    on b.man_id= a.id
)
select a.manager,ISNULL(a.manager,'SUPER BOSS'),b.Level
from CTE_Manager a
join CTE_Manager b
on a.man_id=b.id

实际上我得到了输出:

我在 union all 函数之前检索值。我必须从递归 CTE 中获取所有值。

【问题讨论】:

  • 您的问题到底是什么? “union all is not working”是什么意思?你到底想达到什么目的?向我们展示一些示例数据和预期输出(编辑您的问题,不要在评论中发布)

标签: sql sql-server common-table-expression recursive-query


【解决方案1】:

连接中的 on 子句是错误的。应该是 b.id = a.man_id。

您所做的是选择所有没有经理的经理,然后尝试找到他们的经理。当我怀疑你想要的是他们所有的下属时。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多