gpt4 book ai didi

sql - 统计所有直接或间接向经理汇报的下属

转载 作者:行者123 更新时间:2023-12-04 21:40:37 25 4
gpt4 key购买 nike

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

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

我有一个 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
----------------------

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

最佳答案

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)

关于sql - 统计所有直接或间接向经理汇报的下属,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17878998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com