Сначала я использовал следующий запрос для создания временной таблицы
CREATE TABLE #TBLTEMP(ID int, ParentID int)
INSERT INTO #TBLTEMP(ID,ParentID)
VALUES(1,NULL)
,(2,1)
,(3,2)
,(4,2)
,(5,3)
,(6,NULL)
,(7,6)
,(8,NULL)
,(9,NULL)
Затем я использовал следующий запрос для получения количества дочерних элементов
WITH CTE_1(ParentID) AS(
SELECT ParentID FROM #TBLTEMP T1
UNION ALL
SELECT T2.ParentID FROM CTE_1 c
INNER JOIN #TBLTEMP T2 ON c.ParentID = T2.ID
WHERE T2.ParentID > 0
), CTE_2 AS ( SELECT ID , 0 as cnt FROM #TBLTEMP T3 WHERE NOT EXISTS (SELECT 1 FROM CTE_1 c2 where c2.ParentID = T3.ID))
SELECT ParentID, count(*) as cnt
FROM CTE_1
WHERE ParentID IS NOT NULL
GROUP BY ParentID
UNION
SELECT ID as ParentID, cnt FROM CTE_2
ORDER BY ParentID
Результат:
Ссылка
Обновление 1
Чтобы получить учетную запись для определенного ID:
WITH CTE_1(ParentID) AS(
SELECT ParentID FROM #TBLTEMP T1
UNION ALL
SELECT T2.ParentID FROM CTE_1 c
INNER JOIN #TBLTEMP T2 ON c.ParentID = T2.ID
WHERE T2.ParentID > 0
), CTE_2 AS ( SELECT ID , 0 as cnt FROM #TBLTEMP T3 WHERE NOT EXISTS (SELECT 1 FROM CTE_1 c2 where c2.ParentID = T3.ID)), CTE_3 AS(
SELECT ParentID, count(*) as cnt
FROM CTE_1
WHERE ParentID IS NOT NULL
GROUP BY ParentID
UNION
SELECT ID as ParentID, cnt FROM CTE_2)
SELECT cnt FROM CTE_3 WHERE ParentID = 1