递归SUM Sql Server父子层次结构

时间:2015-05-23 07:37:28

标签: sql sql-server recursion

我们假设我们有下表"#res"

    MatID                           Number  MatName StoreName                StoreID                        SParentID                           Qty
2CA241F6-F48C-4A37-B675-25134C7F84D4    1   Mat1    Store1          194AB76D-01AB-4351-BA6F-5BE0974628F7  00000000-0000-0000-0000-000000000000  12
2CA241F6-F48C-4A37-B675-25134C7F84D4    1   Mat1    Store2          3A34B4D1-5464-461A-9115-20446253FE99  194AB76D-01AB-4351-BA6F-5BE0974628F7  1
2CA241F6-F48C-4A37-B675-25134C7F84D4    1   Mat1    Store3          4594C677-3F55-4E27-8EC9-8209C86FC0CD  3A34B4D1-5464-461A-9115-20446253FE99  1

该表包含一个垫子" Mat1"在3个不同的商店1,2,3中,如SParentID栏" Store Parent" store3是父store2的子节点,store2是父store1(层次结构):

   Store1
     |
   Store2
     |
   Store3

我想将store3中的qty值添加到store2变为2,然后将2添加到父级。请注意,这是一个示例,我想以一般方式执行此操作,无论子项数量多少,并且顶级父级可能具有记录集中不存在的父级!

1 个答案:

答案 0 :(得分:0)

请检查一下这个递归的SELECT查询。我将主表重命名为store。您可以在此参考链接中引用SQL recursive query structure using CTE

;with rcte as (
    select StoreId, SParentId, MatID, ISNULL(Qty,0) Qty from store where SParentId in (select StoreId from store)
    union all
    select 
        store.StoreId, store.SParentId, store.MatID, ISNULL(store.Qty,0) + rcte.Qty as Qty
    from store 
    inner join rcte
        on rcte.SParentId = store.StoreId
)
select
    *
from (
    select rn = ROW_NUMBER() OVER (Partition By StoreId Order By Qty Desc), * from rcte
) t
inner join store s ON s.MatID = t.MatID and s.StoreId = t.StoreId
where t.rn = 1

我希望它有效