I found an extremely helpful article located at: Simplest way to do a recursive self-join in SQL Server?
Suppose in this example that there was another column called "Quantity" that stores integers that looks like so:
PersonID | Initials | ParentID | Quantity
1 CJ NULL 1
2 EB 1 2
3 MB 1 1
4 SW 2 1
5 YT NULL 1
6 IS 5 1
If I requested CJ's hierarchy, it would be
PersonID | Initials | ParentID | Quantity | HasSubordinate
1 CJ NULL 2 1
2 EB 1 1 1
3 MB 1 1 1
4 SW 2 1 0
The column HasSubordinate specifies the last individual in the hierarchy. I would like to display the last person in the hierarchy with the quantities of each preceding row multiplied together. In this case, the quantity would be 2 (2 x 1 x 1 x 1 = 2).
PersonID | Initials | ParentID | Quantity | HasSubordinate
4 SW 2 2 0
My Code:
WITH q AS
(
SELECT *
FROM mytable
WHERE PersonID = 1
UNION ALL
SELECT m.*
FROM mytable m
JOIN q
ON m.parentID = q.PersonID
)
SELECT *
FROM q
WHERE HasSubordinate = 0
Any help is greatly appreciated!!