【问题标题】:I need all the employee under a supervisor我需要主管下的所有员工
【发布时间】:2014-11-19 18:24:27
【问题描述】:

我有以下描述的情况

EmpID      Name        SupervisorID
1          A           9
2          B           8
3          C           1
4          D           3

我需要主管 ID 1 下的所有员工

这里 EmployeeID 3 小于 1 我需要 4 也小于 3

需要以下输出。

EmpID   Name    SupervisorID
3       C       1
4       D       3

【问题讨论】:

  • 你需要递归 CTE
  • “EmpID 名称 SupervisorID 1 A 9 2 B 8 3 C 1 4 D 3”是什么意思?你想要什么???

标签: sql-server sql-server-2008-r2


【解决方案1】:

您需要为此使用递归 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

Fiddle Demo Here

也请看一下这个问题,它和你的问题一样。 Sql server CTE and recursion example

【讨论】:

    【解决方案2】:

    没有人期望 西班牙宗教裁判所 是 HierarchyId。这些天来,每当我看到一个组织结构(就像你在这里看到的那样),我都会使用 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
    

    我看到的优势是,您无需在每次需要回答此类问题时都即时计算层次结构。你做一次就完成了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 2014-12-20
      • 2018-10-29
      • 2015-02-01
      • 1970-01-01
      相关资源
      最近更新 更多