檢查CTE(公用表表達式)以進行遞歸SQL查詢。我在下面包含了一個示例。請讓我知道它是否適用於您的設置。
將@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'
這工作得很好!非常感謝您的快速回復。 – Squared
很高興聽到它! –