3

我已经看到了几个关于如何递归查询自引用表的问题/答案,但我正在努力将我发现的答案应用到每个父母、祖父母等,无论项目位于何处等级制度。

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 中的每个项目以及所有孩子的总金额。

4

2 回答 2

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

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

于 2013-09-27T21:11:08.627 回答
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

于 2013-09-28T05:16:08.130 回答