开发者

T SQL Recursion

开发者 https://www.devze.com 2023-02-03 23:26 出处:网络
Hi my table looks some what like this. OldPart | NewPart | Demand ========================== C|D|3 开发者_如何学PythonF||1

Hi my table looks some what like this.

OldPart | NewPart | Demand
==========================
   C    |    D    |   3
 开发者_如何学Python  F    |         |   1
   A    |    B    |   5
   D    |    E    |   2
   E    |    F    |   0
   B    |    C    |   3
   Z    |         |   1
   M    |         |   7
   Y    |    Z    |   10

What I am trying to do is come up with a final table where the newest part's demand is aggregated and the demand for parts before it are changed to 0.

So my resulting table will be something like this:

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

Thanks in advance.


Your mileage may vary, CTEs are limited. Out-of-the-box they only allow 100 steps deep. (I think the same goes for stored procs)

But ... if you really want a recursive solution... something like this may work. (though it is not super efficient)

Keep in mind, loops and the like may throw this in to a spin.

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 <> ''

results are:

 
F       14
M       7
Z       11
A   B   0
B   C   0
C   D   0
D   E   0
E   F   0
Y   Z   0

Input is:

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


To get the table you describe:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消