2011-01-14 9 views
1

Hallo mein Tisch sieht etwas wie das aus.T SQL Rekursion

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 

Was ich versuche, mit einem Finaltisch kommen zu tun ist, wo die Forderung des neuesten Teils aggregiert und die Nachfrage nach Teilen, bevor es auf 0

geändert werden, so wird meine resultierende Tabelle etwas sein wie folgt:

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 

Vielen Dank im Voraus.

Antwort

0

Leistung kann variieren, CTEs begrenzt sind. Out-of-the-Box erlauben sie nur 100 Stufen tief. (Ich denke, das gleiche gilt für gespeicherte Procs)

Aber ... wenn Sie wirklich eine rekursive Lösung wollen ... so etwas wie kann arbeiten. (obwohl es nicht super effizient ist)

Denken Sie daran, Schleifen und dergleichen können dies in einen Spin werfen.

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

Ergebnisse sind:

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

Eingang ist:

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

den Tisch bekommen Sie beschreiben:

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

, die für die Frage, die ich vor posted up funktioniert gut, aber ich habe vergessen, mehr Ketten von Teilen zu platzieren es. Ich habe es jetzt aktualisiert. Irgendwelche Gedanken? – Vince