2011-01-14 52 views
1

嗨我的表看起来像这样。T SQL递归

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 

在此先感谢。

回答

0

您的里程可能会有所不同,热膨胀系数是有限的。开箱即用,它们只允许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 
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
+0

,对于我之前贴上去的问题的伟大工程,但我忘了零件放置的多个链它。我现在更新了它。有什么想法吗? – Vince 2011-01-14 03:49:45