我得到了下表,我需要在交替的列中对框进行排序,以便在排序时减少移动(真正的机器会做到这一点),但我完全不知道如何做到这一点。
我有:
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。
谢谢。
发布于 2017-03-02 19:50:51
这将生成您正在寻找的输出。在最终选择中将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这假设我们在样本数据中没有任何循环(因此,如果box 2的实际单元格是10506,我们将无法解决此问题)
https://stackoverflow.com/questions/42554298
复制相似问题