聚合自引用表

时间:2013-09-27 21:04:34

标签: sql sql-server sql-server-2008 recursion

我已经看到了关于如何递归查询自引用表的几个问题/答案,但我正在努力应用我发现的答案,汇总到每个父母,祖父母等等,无论项目在哪里坐在层次结构中。

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

数据:

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

如果我在没有过滤和SUMming金额的情况下运行此查询,结果将是:

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

换句话说,我希望看到MyTable中的每个项目以及所有孩子的总金额。

2 个答案:

答案 0 :(得分:4)

那样的东西?

    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

根据以下评论编辑了查询,现在一切正常。

答案 1 :(得分:3)

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