查看递归 SQL 查询的 CTE(通用表表达式)。我在下面包含了一个示例。请让我知道它是否适用于您的设置。
将@INPUT 的值更改为您请求人数的部门(其中 EMPL_STATUS= 'A')。
DECLARE @INPUT INT
SET @INPUT = 1
DECLARE @DEPARTMENT_DATA TABLE
(
DEPTID INT,
REPORTS_TO_DEPT INT,
EFF_STATUS INT
)
INSERT INTO @DEPARTMENT_DATA
SELECT 1, NULL, 1
UNION SELECT 2, 1, 1
UNION SELECT 3, 2, 1
UNION SELECT 4, 1, 1
UNION SELECT 5, 4, 1
DECLARE @EE_Persons_today TABLE
(
ID INT IDENTITY(1,1),
DEPTID INT,
EMPL_STATUS VARCHAR(1)
)
INSERT INTO @EE_Persons_today
SELECT 2, 'A'
UNION ALL SELECT 2, 'A'
UNION ALL SELECT 2, 'A'
UNION ALL SELECT 2, 'A'
UNION ALL SELECT 2, 'B'
UNION ALL SELECT 3, 'A'
UNION ALL SELECT 3, 'A'
UNION ALL SELECT 3, 'B'
UNION ALL SELECT 3, 'A'
UNION ALL SELECT 3, 'A'
UNION ALL SELECT 3, 'A'
UNION ALL SELECT 3, 'A'
UNION ALL SELECT 3, 'B'
UNION ALL SELECT 3, 'A'
UNION ALL SELECT 3, 'A'
UNION ALL SELECT 4, 'B'
UNION ALL SELECT 4, 'A'
UNION ALL SELECT 5, 'A'
UNION ALL SELECT 5, 'A'
UNION ALL SELECT 5, 'B'
UNION ALL SELECT 5, 'A'
; WITH CTE AS
(
SELECT a.DEPTID
FROM @DEPARTMENT_DATA a
WHERE a.DEPTID = @INPUT
UNION ALL
SELECT a.DEPTID
FROM @DEPARTMENT_DATA a
JOIN CTE c
ON a.REPORTS_TO_DEPT = c.DEPTID
)
SELECT COUNT(*)
FROM @EE_Persons_today a
JOIN CTE c
ON a.DEPTID = c.DEPTID
WHERE a.EMPL_STATUS = 'A'