简体   繁体   中英

Aggregate Self-Referencing Table

I've seen several questions/answers on how to recursively query a self-referencing table, but I am struggling to apply the answers I've found to aggregate up to each parent, grandparent, etc. regardless of where the item sits in the hierarchy.

MyTable
-----------
Id
Amount
ParentId

Data:

Id    Amount      Parent Id
 1      100          NULL
 2      50            1
 3      50            1
 4      25            2
 5      10            4

If I were to run this query without filtering, and SUMming amount, the result would be:

Id   SumAmount
 1       235
 2        85
 3        50
 4        35
 5        10

In other words, I want to see each item in MyTable and it's total Amount with all children.

Something like that?

    WITH temp (ID, ParentID, TotalAmount)
AS
(
    SELECT ID, ParentID, Amount
    FROM MyTable
    WHERE NOT EXISTS (SELECT * FROM MyTable cc WHERE cc.ParentID = MyTable.ID)

    UNION ALL

    SELECT MyTable.ID, MyTable.ParentID, TotalAmount + MyTable.Amount
    FROM MyTable
    INNER JOIN temp ON MyTable.ID = temp.ParentID
)

SELECT ID, SUM(TotalAmount) FROM
    (SELECT ID, TotalAmount - (SELECT Amount FROM MyTable M WHERE M.ID = temp.ID) TotalAmount
     FROM temp
     UNION ALL
     SELECT ID, Amount AS TotalAmount FROM MyTable) X
GROUP BY ID

Edited the query based on the comments below, now it all works.

with cte as (
    select t.Id, t.Amount, t.Id as [Parent Id]
    from Table1 as t

    union all

    select c.Id, t.Amount, t.Id as [Parent Id]
    from cte as c
        inner join Table1 as t on t.[Parent Id] = c.[Parent Id]
)

select Id, sum(Amount) as Amount
from cte
group by Id

sql fiddle demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM