2017-03-02 91 views
2

我得到了下面的表格,並且我需要對排列在交替列中的盒子進行排序(真正的機器會這樣做),但我完全喪失瞭如何我能行。基於交替列的T-SQL排序

我:

    Box | Actual_Cell | Best_Cell 
     1 |  10408 | 10101 
     2 |  10509 | 10102 
     3 |  10101 | 10506 
     4 |  10102 | 10408 

我需要:

  (Where is) (Where i will put) 
    Box | Actual_Cell | Best_Cell 
     3 |  10101 | 10506 (Now cell 10101 is free) 
     1 |  10408 | 10101 (Now cell 10408 is free) 
     4 |  10102 | 10408 (Now cell 10102 is free) 
     2 |  10509 | 10102 

這是我的最後一條記錄的Actual_Cell一定是我Best_Cell當前記錄的。

我正在使用MSSQL 2008.

謝謝。

+4

我相當失去了您的意思......您能否添加更多的例子? – Matthew

+2

@Felipe。 。 。這不僅僅是數據。 「Actual_Cell」和「Best_Cell」是什麼意思?訂購數據的規則是什麼?例如,10101之後爲什麼不是10102? Box 3如何最終結束? 「Now cell XXX mean」是什麼意思? –

+0

我們是否保證所有這些擬議掉期鏈都不會形成循環? –

回答

1

這產生你正在尋找的輸出。這可能是有益的改變t.*只是*c.*最終選擇看Chains CTE是如何建立起來的一套互換:

declare @t table (Box int,Actual_Cell int,Best_Cell int) 
insert into @t(Box,Actual_Cell,Best_Cell) values 
(1,10408,10101), 
(2,10509,10102), 
(3,10101,10506), 
(4,10102,10408) 

;With Chains as (
    select Box,Best_Cell,Actual_Cell as Chain,0 as Depth 
    from @t where Best_Cell not in (select Actual_Cell from @t) 
    union all 
    select t.Box,c.Best_Cell,t.Actual_Cell,Depth + 1 
    from Chains c 
     inner join 
     @t t 
      on 
       c.Chain = t.Best_Cell 
) 
select 
    t.* 
from 
    @t t 
     inner join 
    Chains c 
     on 
      t.Box = c.Box 
order by 
    c.Best_Cell, 
    c.Depth 

結果:

Box   Actual_Cell Best_Cell 
----------- ----------- ----------- 
3   10101  10506 
1   10408  10101 
4   10102  10408 
2   10509  10102 

這假定我們樣本數據中沒有任何循環(因此,如果框2的實際單元格爲10506,我們將無法解決此問題)

+0

我很高興,因爲我懷疑你的解釋是正確的。 –

+0

它工作得很好! 謝謝! – Felipe