Tuesday, November 10, 2020

SQL - Hierarchy Node Tree With SUM Total At The Last Node

Each Object has a Parent Object, its Parent Object might have its another own Parent Object as well. Calculate the Sum Total of Time from the root to bottom. This may help you in calculating total time taken in project management that has a complex workflow design.  

CREATE TABLE WaitingTime ( OBJECT VARCHAR(10) , ParentObject VARCHAR(10) , WaitingTime INT )
INSERT INTO WaitingTime values ( 'A' ,NULL, 1)
INSERT INTO WaitingTime values ( 'B' ,'A', 2)
INSERT INTO WaitingTime values ( 'C' ,'A', 3)
INSERT INTO WaitingTime values ( 'D' ,'B', 4)
INSERT INTO WaitingTime values ( 'E' ,'B', 5)
INSERT INTO WaitingTime values ( 'F' ,'C', 6)
INSERT INTO WaitingTime values ( 'G' ,'C', 7)
 
 
;With cte AS (
SELECT *, WaitingTime as TotalWaitingTime FROM
waitingTime
UNION ALL
SELECT w.*, TotalWaitingTime+ w.WaitingTime 
FROM WaitingTime w
JOIN cte
ON w.ParentObject = cte.Object
)
SELECT OBJECT , ParentObject , WaitingTime , max(TotalWaitingTime)
FROM cte
GROUP BY OBJECT , ParentObject , WaitingTime

No comments:

Post a Comment