4

我在一项任务中遇到了问题。

我需要统计所有直接或间接向特定经理汇报的下属(不同的)

我有一张Employee这样的桌子:

EMPLOYEE_ID Int,
MANAGER_ID Int,
EMPLOYEE_NAME varchar(200)

例子:

            Alex(1)
    --------------------
    Jhon(2)          Kevin(3)
------------------------------
Mike(4) Amanda(5)  Tom(6) Jery(7)

我只能计算直接向经理汇报的员工:

SELECT 
    MANAGER_ID
   ,COUNT(MANAGER_ID) as SubCount
FROM [dbo].[EMPLOYEE]
GROUP BY MANAGER_ID

但结果我有这样的事情:

Manager_ID | SubCount
----------------------
1          | 2
2          | 2
3          | 2
----------------------

反而:

Manager_ID | SubCount
----------------------
1          | 6
2          | 2
3          | 2
----------------------

我会很高兴有任何建议或想法如何做到这一点。

4

2 回答 2

4
declare @t table(EMPLOYEE_ID Int,
MANAGER_ID Int,
EMPLOYEE_NAME varchar(200))
insert @t values(1,null,'Alex'),(2,1,'Jhon'),(3,1,'Kevin'),
(4,2,'Mike'),(5,2,'Amanda'),(6,3,'Tom'),(7,3,'Jerry')

;with a as
(
select EMPLOYEE_ID boss,EMPLOYEE_ID from @t t
  where exists (select 1 from @t where t.EMPLOYEE_ID = MANAGER_ID)
union all
select a.boss, t.EMPLOYEE_ID
from @t t join a on t.MANAGER_ID = a.EMPLOYEE_ID
)
--subtracting 1 because it is also counting the manager
select boss, count(*)-1 SubCount from a group by boss
option (maxrecursion 20)
于 2013-07-26T11:19:54.160 回答
3

您需要为此使用递归 CTE:

with managers as (
      select employee_id, manager_id, 1 as level
      from employees e
      union all
      select e.employee_id, m.manager_id, e.level+1
      from managers m join
           employees e
           on m.manager_id = e.employee_id
     )
select m.manager_id, count(*)
from managers m
group by m.manager_id;

递归 CTE 创建所有员工/经理对。最后一个查询进行聚合和计数。

编辑:

听起来员工/经理关系中存在周期。我认为以下解决了这个问题(我现在没有可用的 SQL Server 来测试它):

with managers as (
      select employee_id, manager_id, 1 as level
      from employees e
      union all
      select e.employee_id, m.manager_id, e.level+1
      from managers m join
           employees e
           on m.manager_id = e.employee_id
      where e.employee_id not in (select employee_id from managers)
     )
select m.manager_id, count(*)
from managers m
group by m.manager_id;
于 2013-07-26T10:45:04.070 回答