Get all employee who directly or indirectly reports to an employee, with hierarchy level no

后端 未结 2 837
予麋鹿
予麋鹿 2021-02-06 12:51

I have a Employee table like

emp_id bigint,
reports_to bigint,
emp_name varchar(20),
Constraint [PK_Emp] Primary key (emp_id),
Constraint [FK_Emp] Foreign key (r         


        
2条回答
  •  一个人的身影
    2021-02-06 13:31

    You could use a recursive CTE:

    ; with  CTE as 
            (
            select  emp_id
            ,       reports_to
            ,       emp_name
            ,       1 as level
            from    Emp
            where   emp_name = 'Sumanta'
            union all
            select  child.emp_id
            ,       child.reports_to
            ,       child.emp_name
            ,       level + 1
            from    Emp child
            join    CTE parent
            on      child.reports_to = parent.emp_id
            )
    select  *
    from    CTE
    

    Example at SQL Fiddle.

提交回复
热议问题