基于交替列的T-SQL排序

时间:2017-03-02 11:31:33

标签: sql sql-server sql-server-2008 tsql

我得到了下表,我需要对备用列中的框进行排序,以便在排序时减少移动(真正的机器会这样做),但我完全迷失了我的能力。

我有:

    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。

感谢。

1 个答案:

答案 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,我们将无法解决此问题)