This will get the full report
SELECT t1.DEPARTMENT_ID
, t1.PARENT_DEP_ID
, t1.DEPARTMENT
, Sum(t2.Amount) Amount
FROM TREE_DATA t1
INNER JOIN TREE_DATA t2
ON t1.DEPARTMENT = SUBSTR(t2.DEPARTMENT, 1, LENGTH(t1.DEPARTMENT))
WHERE t1.Amount = 0
GROUP BY t1.DEPARTMENT_ID, t1.PARENT_DEP_ID, t1.DEPARTMENT
UNION ALL
SELECT DEPARTMENT_ID
, PARENT_DEP_ID
, DEPARTMENT
, Amount
FROM TREE_DATA
WHERE Amount > 0
ORDER BY DEPARTMENT
The first query get the rolling sum by hacking the structure of the Department name for the oens without the amounts, the second one get the leafs.
The first query cannot show the leafs, as they will get grouped.
I haven't found any column combination to get the same order, the leafs seems to be unordered.
SQLFiddle demo
I've tried to write a recursive CTE
, but it's not possible to have aggregate function, such as SUM
in it.