【问题标题】:Recursive SUM Sql Server parent-child-hierarchy递归 SUM Sql Server 父子层次结构
【发布时间】:2015-05-25 13:52:59
【问题描述】:

假设我们有下表“#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

该表在 3 个不同的商店 1、2、3 中包含一个垫子“Mat1”,如 SParentID 列“Store Parent”所示,store3 是父 store2 的子元素,store2 是父 store1(层次结构):

   Store1
     |
   Store2
     |
   Store3

我想把store3中qty的值加到store2变成2,然后把2加到父代。请注意,这是一个示例,无论孩子的数量如何,我都想以一般方式进行操作,并且最高父级可能有记录集中不存在的父级!

【问题讨论】:

标签: sql sql-server recursion


【解决方案1】:

您能否检查一下这个递归 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

我希望它有效

【讨论】:

    猜你喜欢
    • 2021-07-04
    • 2015-11-23
    • 1970-01-01
    • 2017-02-04
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 2015-09-07
    • 1970-01-01
    相关资源
    最近更新 更多