让所有直接或间接向主管报告参与主管的下属

时间:2014-02-13 14:56:40

标签: sql-server linq linq-to-sql

我需要让所有下属指导和下一个指导下属参与主管Id。

我有一张桌子

EmployeeId int,SupervisorId int

示例数据:

    EmployeeId | SupervisorId 
    ----------------------
    1          | 4
    2          | 4
    4          | 6
    5          | 4
    7          | 6
    8          | 6
    ----------------------

我的参数是主管6,我希望得到直接和间接的下属。

接受LINQ或MSSQL查询。非常感谢。

3 个答案:

答案 0 :(得分:2)

 declare @employeeId as integer = 706
 declare @EmployeeList table
 (
       EmployeeId int
 )
 declare @EmployeeList1 table
 (
       EmployeeId int
 )

 insert into @EmployeeList1
 select EmployeeId
 from Employee
 where ImmediateSupervisorId = @employeeId
 order by 1 

 insert into @EmployeeList
 select EmployeeId
 from Employee
 where ImmediateSupervisorId in (select employeeId from @EmployeeList1)

 select EmployeeId
 from Employees

 where (sr.ImmediateSupervisorId in (select employeeId from @EmployeeList)              
or sr.ImmediateSupervisorId = @employeeId)     

答案 1 :(得分:0)

在SQL中你可以这样做:

SELECT EmployeeID FROM myTable
WHERE SupervisorID IN (SELECT EmployeeID 
                       FROM myTable 
                       WHERE SupervisorID = 6)
OR SupervisorID = 6;

我不知道如何将其表示为LINQ查询。

答案 2 :(得分:0)

您是否正在尝试让所有主管下游的员工? 如果是这样的话,如果你可以最多降低9级,那就行了(尽管它很粗糙)。

    SELECT e.* FROM Employee e
        LEFT JOIN Employee s1 ON s1.EmployeeID = e.SupervisorId
        LEFT JOIN Employee s2 ON s2.EmployeeID = s1.SupervisorId
        LEFT JOIN Employee s3 ON s3.EmployeeID = s2.SupervisorId
        LEFT JOIN Employee s4 ON s4.EmployeeID = s3.SupervisorId
        LEFT JOIN Employee s5 ON s5.EmployeeID = s4.SupervisorId
        LEFT JOIN Employee s6 ON s6.EmployeeID = s5.SupervisorId
        LEFT JOIN Employee s7 ON s7.EmployeeID = s6.SupervisorId
        LEFT JOIN Employee s8 ON s8.EmployeeID = s7.SupervisorId
        LEFT JOIN Employee s9 ON s9.EmployeeID = s8.SupervisorId
    WHERE
        e.SupervisorID = 6
        OR ISNULL(s2.EmployeeId, 0) = 6
        OR ISNULL(s3.EmployeeId, 0) = 6
        OR ISNULL(s4.EmployeeId, 0) = 6
        OR ISNULL(s5.EmployeeId, 0) = 6
        OR ISNULL(s6.EmployeeId, 0) = 6
        OR ISNULL(s7.EmployeeId, 0) = 6
        OR ISNULL(s8.EmployeeId, 0) = 6
        OR ISNULL(s9.EmployeeId, 0) = 6

(请注意,这只有在主管自己在表中时才有效。)