递归SQL自连接

西蒙

我有以下的员工表之间有外键关系EmpIDManagerID

员工表

在此处输入图片说明

期望的输出

我希望能够按>从最高经理到最底层的层次结构顺序显示员工姓名,而EmpID是层次结构底部的员工ID。

在此处输入图片说明

我知道我可以通过使用以下SQL将表与其自身连接来获得所需的输出。

select e1.empID, e1.DeptID, e2.Name + ' > ' + e1.Name as Description
from employee e1
left join employee e2
on e1.managerId = e2.empId

我也知道我可以在上述查询中添加更多的左联接,以获得所需的输出。但是对层次结构的深度没有限制,因此我想它将需要动态完成。

任何帮助将不胜感激

戈登·利诺夫(Gordon Linoff)

您需要递归CTE:

with e as (
      select cast(name as varchar(max)) as list, empId, 0 as level
      from employees
      where managerID is null
      union all
      select e.list + '>' + e2.name, e2.empId, level + 1
      from e join
           employees e2
           on e.empId = e2.managerId
     )
select e.*
from e
where not exists (select 1
                  from employees e2
                  where e2.managerId = e.empId
                 );

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章