Tsql SQL递归

Tsql SQL递归,tsql,recursion,aggregate,Tsql,Recursion,Aggregate,嗨,我的桌子看起来像这样 OldPart | NewPart | Demand ========================== C | D | 3 F | | 1 A | B | 5 D | E | 2 E | F | 0 B | C | 3 Z | | 1 M |

嗨,我的桌子看起来像这样

OldPart | NewPart | Demand
==========================
   C    |    D    |   3
   F    |         |   1
   A    |    B    |   5
   D    |    E    |   2
   E    |    F    |   0
   B    |    C    |   3
   Z    |         |   1
   M    |         |   7
   Y    |    Z    |   10
我想做的是得出一个最终的表格,其中汇总了最新零件的需求,并将零件的需求更改为0

因此,我的结果表如下所示:

OldPart | NewPart | Demand
==========================
   C    |    D    |   0
   F    |         |   14
   A    |    B    |   0
   D    |    E    |   0
   E    |    F    |   0
   B    |    C    |   0
   Z    |         |   11
   M    |         |   7
   Y    |    Z    |   0

提前感谢。

要获得您描述的表格:

SELECT OldPart
     , null   as newPart
     , (Select sum(demand)
          from myTable
         where newPart is not null
       ) as Demand
  from myTable
 where newPart is null
 UNION ALL
select oldPart,newpart,0
  from myTable
 where newPart is not null

您的里程可能会有所不同,CTE是有限的。开箱即用,只允许100步深。(我认为存储过程也是如此)

但是。。。如果你真的想要一个递归的解决方案。。。像这样的东西可能有用。(虽然不是超级高效)

请记住,循环之类的东西可能会使这一切变得混乱

with recurse as (
    select * from #t
    union all
    select t2.OldPart, t2.NewPart, t.Demand + t2.Demand as Demand from recurse t
    join #t t2 on t.NewPart = t2.OldPart
)


select * from (
select OldPart, '' NewPart ,MAX(Demand) Demand from recurse
where OldPart in (select OldPart from #t where NewPart = '')
group by OldPart 
) X 
union all 
select distinct OldPart, NewPart, 0 
from #t 
where NewPart <> ''

这对于我之前发布的问题非常有效,但我忘了在上面放置更多的零件链。我现在已经更新了。有什么想法吗? F 14 M 7 Z 11 A B 0 B C 0 C D 0 D E 0 E F 0 Y Z 0
create table #t (OldPart varchar, NewPart varchar, Demand int) 

go 

insert #t 
select
   'C'   ,  'D'     , 3
  union all
select
   'F'     ,   ''     ,  1
  union all
select
   'A'     ,   'B'    ,  5
  union all
select
   'D'     ,   'E'    ,  2
   union all
select
   'E'     ,   'F'    ,  0

  union all
select
   'B'    ,    'C'    ,  3

  union all
select
   'Z'    ,    ''    ,   1
   union all
select
   'M'    ,   ''     ,   7
  union all
select
   'Y'    ,    'Z'   ,   10