You are right, your article is what you needed.
I formatted the data first into a fooBar temp table:
SELECT b.id
, foo_id
, ISNULL(f.carryover_id, foo_id) as carryover_id
, b.amount
, ROW_NUMBER() OVER(
PARTITION BY ISNULL(f.carryover_id, foo_id)
ORDER BY b.id asc) as rowNmbr
INTO #fooBar
FROM #bar as b
INNER JOIN #foo as f
ON b.foo_id = f.id;
The first row in the WITH
is the top level. Then it recursively goes through each level. The rowNmbr is the level.
WITH summarizedFoo(rowNmbr, id, foo_id, carryover_id, amount, totalAmount)
AS
(
SELECT f.rowNmbr
, f.id
, f.foo_id
, f.carryover_id
, ISNULL(f.amount,0) as amount
, ISNULL(f.amount,0) as totalAmount
FROM #fooBar as f
WHERE f.rowNmbr = 1
UNION ALL
SELECT f.rowNmbr
, f.id
, f.foo_id
, f.carryover_id
, ISNULL(f.amount,0) as amount
, CAST((ISNULL(f.amount,0)
+ ISNULL(s.totalAmount,0)) as decimal) as totalAmount
FROM #fooBar as f
INNER JOIN summarizedFoo as s
ON f.carryover_id = s.carryover_id
AND f.rowNmbr = s.rowNmbr +1
)
SELECT rowNmbr, id, foo_id, carryover_id, amount, totalAmount
FROM summarizedFoo
I did this in T-SQL, but to make this work in your fiddler
Here is the PostgreSQL version:
Create a fooBar table (could be a view):
INSERT INTO fooBar
SELECT CAST(b.id as INTEGER)
, CAST(foo_id as INTEGER)
, CAST(CASE WHEN f.carryover_id is NULL THEN foo_id ELSE f.carryover_id END as INTEGER) as carryover_id
, CAST(b.amount as DECIMAL)
, CAST(ROW_NUMBER() OVER(PARTITION BY CASE WHEN f.carryover_id is NULL THEN foo_id ELSE f.carryover_id END ORDER BY b.id asc) as INTEGER) as rowNmbr
FROM bar as b
INNER JOIN foo as f
ON b.foo_id = f.id;
Here is the WITH RECURSIVE
:
WITH RECURSIVE summarizedFoo(rowNmbr, id, foo_id, carryover_id, amount, totalAmount)
AS
(
SELECT f.rowNmbr, f.id, f.foo_id, f.carryover_id
, f.amount
, f.amount
FROM fooBar as f
WHERE f.rowNmbr = 1
UNION ALL
SELECT f.rowNmbr, f.id, f.foo_id, f.carryover_id
, f.amount
, f.amount + s.totalAmount
FROM fooBar as f
INNER JOIN summarizedFoo as s
ON f.carryover_id = s.carryover_id
AND f.rowNmbr = s.rowNmbr +1
)
SELECT rowNmbr, id, foo_id, carryover_id, amount, totalAmount
FROM summarizedFoo
I tested in SSMS(T-SQL version) and Fiddler(PostgreSQL), and verified the results in Excel.
Here is Fiddler of the solution:
http://sqlfiddle.com/#!15/a7822/3