2016-02-17 50 views
-1

我有一個名爲BusinessAssociate一個數據庫表,該表中對複雜的緣故有2列入門基於活動記錄的列值

BusinessAssociateKey int 
AmalgamatedIntoBAKey int 

使用,我們可以加入其它表的BusinessAssociateKey,和一個這些表(BACorporateStatus)告訴我們該BusinessAssociate是活動還是合併。

讓我們假設業務助理鍵123456被合併到BA的關鍵987654,在同一個表會出現一排,用987654一BusinessAssociateKey,而該行很可能是過於合併,例如進入BusinessAssociateKey 283746.

是否有每個BusinessAssociateKey找到活動(未合併)業務夥伴的方法?

鏈的數目是未知的,可能是沒有或可能是n。

編輯:這是一個SQL小提琴,http://sqlfiddle.com/#!9/1e886/1在這個例子中BusinessAssociateKey 56781沒有合併,所以BusinessAssociateKey 123尚存/主動BA關鍵是56781.

回答

-1

遞歸:

;with rec_cte as(
select b1.BusinessAssociateKey, b1.AmalgamatedIntoBAKey, 1 as rn 
    from BusinessAssociate b1 left outer join BusinessAssociate b2 on b1.BusinessAssociateKey = b2.AmalgamatedIntoBAKey 
    where b2.BusinessAssociateKey is null 
union all 
select c.BusinessAssociateKey, b.AmalgamatedIntoBAKey, c.rn + 1 
    from rec_cte c inner join BusinessAssociate b on c.AmalgamatedIntoBAKey = b.BusinessAssociateKey 
    where b.AmalgamatedIntoBAKey is not null), 
cte as(
select BusinessAssociateKey, max(rn) as rn 
    from rec_cte 
    group by BusinessAssociateKey) 

select r.BusinessAssociateKey, r.AmalgamatedIntoBAKey 
    from rec_cte r inner join cte c on r.BusinessAssociateKey = c.BusinessAssociateKey and r.rn = c.rn 
    option (maxdop 0) 
+0

正確的,但如果你看看小提琴讓說我的生意asociate關鍵是123,我想「走」的鏈條,並獲得最後的有效BA重點 – andrewb

+0

我糾正查詢 – xLiSPirit

0

待辦事項與桌子自我加入。在這裏,我添加了行號以使用自連接來獲取最後的記錄。

Select F.Nbr, F.BusinessAssociateKey, F.AmalgamatedIntoBAKey 
    From 
    (Select row_number() Over(order by (select 1)) as Nbr, E.BusinessAssociateKey, E.AmalgamatedIntoBAKey 
    From BusinessAssociate E 
    ) F 
    LEFT OUTER JOIN 
    (Select row_number() Over(order by (select 1)) as Nbr, E.BusinessAssociateKey, E.AmalgamatedIntoBAKey 
    From BusinessAssociate E 
    ) K 
    ON F.AmalgamatedIntoBAKey = K.BusinessAssociateKey 
    where K.Nbr IS NULL 

http://sqlfiddle.com/#!6/88b53/26

+0

關閉,但我想要的結果是原始的BusinessAssociateKey(123),我希望AmalgamatedIntoBAKey爲56781 – andrewb