来自员工表的Manager / Supervisor / Employee层次结构的SQL报告

时间:2017-03-06 17:03:10

标签: mysql reporting-services ssrs-2012

我有一个Employee表,显示员工ID及其经理ID。管理人员希望报告不仅能显示他的直接报告,还能报告他本人以及向直接下属报告的所有员工。

例如,我的表格将包含以下表格:

table

我需要为Manager1编写的报告将包含他的信息以及他的直接报告(Supervisor1和Supervisor2)及其报告(Employee1到Employee4)。

我可以使用某种类型的连接或任何其他代码将这一个表与自身多次联系以获取间接报告吗?

1 个答案:

答案 0 :(得分:2)

您正在寻找recursive Common Table Expression

declare @Employees table (EmpID nvarchar(15), MgrID nvarchar(15));

insert into @Employees values ('Manager1', null);
insert into @Employees values ('Supervisor1', 'Manager1');
insert into @Employees values ('Employee1', 'Supervisor1');
insert into @Employees values ('Employee2', 'Supervisor1');
insert into @Employees values ('Supervisor2', 'Manager1');
insert into @Employees values ('Employee3', 'Supervisor2');
insert into @Employees values ('Employee4', 'Supervisor2');

with Employees (MgrID, EmpID, [Rank], [Reports]) as
(
    select
      MgrID
    , EmpID
    , 0 'Rank'
    , cast(EmpID as nvarchar(max)) 'Reports'
    from @Employees
    where MgrID is null
    union all
    select
      e.MgrID 
    , e.EmpID
    , [Rank] + 1
    , [Reports] + '; ' + e.EmpID
    from @Employees e
    inner join Employees on Employees.EmpID = e.MgrID
)
select *
from Employees
where Reports like 'Manager1%'
order by [Rank];