我在数据库中有一个表
EmployeeID TeamLeadID
2 1
3 2
4 3
5 NULL
1 NULL
6 1
7 2
8 3
现在我想要的是检索给定TeamLeadsID
EmployeeID
(即所有上层)
对于EmployeeID = 2
我应该得到ans 1(因为TeamleadID
我们没有EmployeeId = 1
)
对于EmployeeID = 4
我应该得到3,2和1(因为4> Teamlead是3,3 - > Teamlead是2,2 - > TeamLead是1)
同样,EmployeeID = 7
我应该只获得2和1
而5& 1从表格中可以清楚地看到它应该是空的
答案 0 :(得分:1)
最低努力将是:
编写如下查询:
Declare @EmployeeID int = 4
; with list(EmployeeID, TeamLeadID) as (
Select EmployeeID, TeamLeadID From Employees Where EmployeeID = @EmployeeID
Union All
Select e.EmployeeID, e.TeamLeadID From Employees E
Inner Join list l On l.TeamLeadID = E.EmployeeID
Where E.TeamLeadID is not NULL
)
Select TeamLeadID From list