Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基于交替列的T-SQL排序_Sql_Sql Server_Sql Server 2008_Tsql - Fatal编程技术网

基于交替列的T-SQL排序

基于交替列的T-SQL排序,sql,sql-server,sql-server-2008,tsql,Sql,Sql Server,Sql Server 2008,Tsql,我得到了下表,我需要在交替的列中对框进行排序,以减少排序时的移动(一台真正的机器可以做到这一点),但我完全不知道如何才能做到这一点 我有:     Box | Actual_Cell | Best_Cell      1 | 10408 | 10101      2 | 10509 | 10102      3 | 10101 | 10506      4 | 10102 | 10408 我需要: (

我得到了下表,我需要在交替的列中对框进行排序,以减少排序时的移动(一台真正的机器可以做到这一点),但我完全不知道如何才能做到这一点

我有:

    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
也就是说,最后一条记录的my
实际\u单元格
必须是当前记录的my
最佳\u单元格

我正在使用MSSQL 2008


谢谢。

这将生成您想要的输出。在最终选择中,将
t.*
更改为
*
c.*
,以查看
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,我们将无法解决此问题)

我完全不明白您的意思。。。你能再举几个例子吗?@Felipe。这不仅仅是数据。
实际单元格
最佳单元格
是什么意思?数据排序的规则是什么。例如,为什么10102不在10101之后?方框3怎么会先结束?“现在的XXX单元”是什么意思?我们能保证所有这些提议的交换链不会形成一个循环吗?奇怪的是,为什么这个不清楚的问题会有几个循环votes@GordonLinoff-我相信(并以我的回答为基础)此表代表了要执行的一组动作。每一步都是从
实际_单元格
中取出一些东西,然后将该项目放入
最佳_单元格
。目标是按顺序安排这些移动,以便没有移动尝试将项目放置到已占用的单元格中。这些移动已经被计算过了,(不同寻常的)这里的单元格是一些外部概念,而不是对行和列的交叉点的引用。我正在投票,因为我怀疑你的解释是正确的。