我有一个下面描述的情况
EmpID Name SupervisorID
1 A 9
2 B 8
3 C 1
4 D 3
我需要主管身份证1下的所有员工
这里EmployeeID 3低于1我需要4也低于3
需要输出以下内容。
EmpID Name SupervisorID
3 C 1
4 D 3
答案 0 :(得分:2)
你需要使用Recursive CTE。试试这个,
With CTE as
(
select EmpID,Name,SupervisorID from Emp
where SupervisorID =1
Union All
select a.EmpID,a.Name,a.SupervisorID from Emp as a
inner join CTE b on a.SupervisorID= b.EmpID
)
select * from CTE
请看一下这个问题,它和你的问题一样。 Sql server CTE and recursion example
答案 1 :(得分:0)
没有人希望西班牙宗教裁判所成为HierarchyId。这些天,每当我看到一个org结构(就像你在这里的那个)时,我就会找到HierarchyId数据类型。从本质上讲,它允许您回答诸如“这个值下的哪个值是什么?”之类的问题。和“这个属于哪个价值?”。以下是我实现它的方法:
alter table dbo.Employee add OrgStructure HierarchyId null;
with h as (
select EmployeeId, SupervisorId, '/' + cast(EmployeeId as varchar) + '/' as h
from dbo.Employee as e
where e.SupervisorId is null --employees w/o a supervisor
union all
select e.EmployeeId, e.SupervisorId, h.h + '/' + cast(EmployeeId as varchar) + '/'
from dbo.Employee as e
join h
on e.SupervisorId = h.SupervisorId
)
update e
set OrgStructure = h.h
from dbo.Employee as e
join h
on e.EmployeeId = h.EmployeeId;
create index [IX_Employee_OrgStructure] on dbo.Employee (OrgStructure)
现在已经完成了繁重的工作,实际上回答你的问题是微不足道的:
select *
from dbo.Employee as supervisor
join dbo.Employee as reports
on reports.OrgStructure.IsDescendantOf(supervisor.OrgStructure)
where supervisor.EmployeeId = 1
我看到的优点是,每次您需要回答此类问题时,您都不会动态计算层次结构。你做了一次而且你已经完成了。