2011-01-14 3 views
1

안녕하세요. 내 표가 이렇게 생겼습니다. 그것은 그래서 내 결과 테이블 뭔가 될 것입니다 0T 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 

이 같은 : 사전에

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

귀하의 마일리지가 다를 수 있습니다, 열팽창 계수가 제한됩니다. Out-of-the-box는 100 단계 만 허용합니다. (나는 같은 procs 저장된 것 같아)

하지만 ... 당신이 정말로 재귀 솔루션을 원한다면 ... 이런 식으로 뭔가가 수 있습니다. (비록 효율적이지는 않지만)

루프와 같은 것들이 회전 속도를 늦출 수 있습니다.

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