我遇到了一项任务问题。
我需要统计直接或间接向特定经理报告的所有下属(不同)
我有一个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
----------------------
如果有任何建议或想法,我会很高兴。
答案 0 :(得分: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)
答案 1 :(得分: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;