I am currently creating a Organizational Chart and I need a total count of all the nodes under a certain employee.
I researched that I need to use recursive SQL. But it seems to not be working in my query. Instead I repeatedly (I know this seems wrong) put the query in a temp table and add the Children of the employee and so on. There is a sample data:
INSERT INTO @T (ID, name, AdvisorID) VALUES
(1, 'Euler', NULL),
(2, 'Lagrange', 1),
(3, 'Laplace', 1),
(4, 'Fourier', 2),
(5, 'Poisson', 2),
(6, 'Dirichlet', 4),
(7, 'Lipschitz', 6),
(8, 'Klein', 6),
(9, 'Lindemann', 8),
(10, 'Furtwangler', 8),
(11, 'Hilbert', 9),
(12, 'Taussky-Todd', 10);
SELECT ID
, name
, AdvisorID
, (SELECT COUNT(*) FROM @T WHERE AdvisorID = e.ID) AS ChildrenCount
INTO #Temp1
FROM @T e
SELECT *
, (SELECT ISNULL((SUM(ChildrenCount)+e.ChildrenCount),0) FROM #Temp1 WHERE AdvisorID = e.ID) AS Total
INTO #Temp2
FROM #Temp1 e
SELECT *
, (SELECT ISNULL((SUM(Total)+e.ChildrenCount),0) FROM #Temp2 WHERE AdvisorID = e.ID AS Total2
INTO #finalTemp
FROM #Temp2 e
and so on...
Thanks for the help. I just want to optimize my repetitive code because it will take too long to load in the page.
What I have tried:
How to find out total number of immediate children of a parent in HierarchyID – SQLServerCentral[
^]
postgresql - Recursive SQL - count number of descendants in hierarchical structure - Stack Overflow[
^]