如何列出特定员工的所有员工?

时间:2013-11-16 07:15:44

标签: sql sql-server tsql

Select * 
from IWIN..VW_EMPMASTER E 
where E.em_teamcd = 'C0015'  

给了我:

C3892
C6331

是紧接在C0015

之下的员工列表
Select * 
from IWIN..VW_EMPMASTER E 
where E.em_teamcd = 'C3892' 

列出了紧接在C3892

之下的所有14名员工

我希望得到直接或间接来自'em_empid'C0015的所有员工的名单......而不仅仅是直接来自他的员工。我怎么能这样做?

最高层次结构为5。

1 个答案:

答案 0 :(得分:0)

假设em_teamcd是经理的标识符,em_empid标识员工(包括经理),您可以使用recursive query using a common table expression,我在文档中的示例中对此进行了调整:

WITH Tree (em_empid, em_teamcd, level)
AS
(
-- Anchor member definition
    SELECT e.em_empid, e.em_teamcd, 0 AS Level
    FROM dbo.VW_EMPMASTER AS e
    WHERE em_teamcd = 'C0015'
    UNION ALL
-- Recursive member definition
    SELECT e.em_empid, e.em_teamcd, Level + 1
    FROM dbo.VW_EMPMASTER AS e
    INNER JOIN Tree AS d ON e.em_teamcd = d.em_empid
)
-- Statement that executes the CTE
SELECT * FROM Tree WHERE Level <= 5

em_empid将保留所有员工C0015以上。

包含一些虚假数据的示例SQL Fiddle