查找层次结构的顶部

时间:2019-06-05 23:16:51

标签: sql sql-server

我有下表:员工

employee   emp_id manager  manager_id
a          1      x        1
b          2      a        1
c          3      b        2

我试图证明x 1是a,b和c的最高经理,即使a 1是b 2的经理,而b 2是c 3的经理。这是我要完成的工作:

employee employee_id top_manager top_manager_id
a        1           x           1 
b        2           x           1
c        3           x           1

我尝试过的代码

 WITH 
    report AS 
    (
     SELECT employee, employee_id, top_manager, top_manager_id
       FROM employees
      UNION ALL
     SELECT e.employee, e.employee_id, e.top_manager, e.top_manager_id
       FROM dbo.employees e
      INNER JOIN report r ON e.employee_id = r.top_manager_id 
    )
     SELECT employee, employee_id, top_manager, top_manager_id
       FROM report

1 个答案:

答案 0 :(得分:0)

使用recursive CTE

;WITH all_managers_per_employee (employee_id, manager, manager_id)
AS
(
   select employee_id, manager, manager_id from employees -- Anchor member
   UNION ALL
   select all_managers_per_employee.employee_id, line_manager.manager, line_manager.manager_id -- Recursive member; references cte table, all_managers_per_employee .
   from all_managers_per_employee 
     join employees line_manager on line_manager.employee = all_managers_per_employee.manager
   where line_manager.manager <> line_manager.employee
),
tops (employee)
AS
(
    select distinct manager as employee
    from employees
    where manager not in (select employee from employees where manager<>employee)
)
select employees.employee, employees.employee_id, tops.employee as top_manager, all_managers_per_employee.manager_id as top_manager_id 
from all_managers_per_employee
    join tops on tops.employee = all_managers_per_employee.manager
    join employees on employees.employee_id = all_managers_per_employee.employee_id
order by 3,1;