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

后端 未结 2 835
予麋鹿
予麋鹿 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:27

    Using Common_Table_Expression we can write like this

    WITH Employee_CTE(employeeid,hierarchy_level,name) AS  
    (  
       SELECT employeeid,1 as level,name from employee where employeeid=1 
       UNION ALL  
       SELECT e.employeeid,level +1, e.name 
       from employee e   
       INNER JOIN Employee_CTE c ON e.employeeid = c.managerid  
    )  
    SELECT * FROM Employee_CTE order by employeeid  
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题