Dit forsøg på at bruge LEAD
vil ikke fungere, da det ikke summerer alle tidligere niveauer, og dets ID'er skal være sekventielle.
Eksploder det fulde hieraki for hver medarbejder først, således at hver medarbejder inkluderes én gang pr. hierarkiniveau:
;WITH cte
AS
(
SELECT e.ID, e.Name, e.ID as sub_ID
FROM @Employees e
-- no WHERE-condition to get all employees
UNION ALL
SELECT
c.ID, c.Name -- keep the initial employee
,e.ID as sub_ID
FROM @Employees e
INNER JOIN cte c ON c.sub_ID = e.ParentID
)
SELECT
c.ID
,c.Name
-- parent level
,sum(case when c.id = s.EmployeeID then s.Quantity else 0 end) AS ParentSumSales
-- child level
,sum(case when c.id <> s.EmployeeID then s.Quantity else 0 end) AS ChildSumSales
FROM cte c
LEFT JOIN @Sales as s
ON s.EmployeeID = c.sub_ID
group by c.Name, c.id