2011-01-14 47 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