gpt4 book ai didi

sql - 更新语句以重新排序表队列

转载 作者:行者123 更新时间:2023-12-04 14:25:33 24 4
gpt4 key购买 nike

有一张表,测试数据如下

PKId         EqId    Worker     Queue
1 1 Worker1 1
3 1 Worker3 3
2 1 Worker2 4
4 1 Worker4 7

需要更新将轮换 Workers 的表,以便在更新语句之后数据如下所示

PKId         EqId   Worker  Queue
1 1 Worker1 7
3 1 Worker3 1
2 1 Worker2 3
4 1 Worker4 4

最佳答案

您几乎可以通过连接来做到这一点:

select pkid, eqid, worker, queue, tprev.queue as newqueue
from t left outer join
t tprev
on t.pkid = tprev.pkid + 1

但是,对于 PkID = 1,您最终会得到 NULL。因此,我们需要将其添加到:

select pkid, eqid, worker, queue, coalesce(tprev.queue, lastone.queue) as newqueue
from t left outer join
t tprev
on t.pkid = tprev.pkid + 1 cross join
(select top 1 queue from t order by pkid desc) as lastone

如果你真的想更新,那么我们可以把它放在一个更新语句中:

update t
set queue = newqueue
from (select pkid, eqid, worker, queue,
coalesce(tprev.queue, lastone.queue) as newqueue
from t left outer join
t tprev
on t.pkid = tprev.pkid + 1 cross join
(select top 1 queue from t order by pkid desc) as lastone
) newt
where t.pkid = newt.pkid

我意识到您的主键可能有漏洞。在这种情况下,从以下查询开始:

select t.*, newQueue
from (select t.*,
(select top 1 queue from t t2 where t2.pkid < t.pkid order by t2.pkid desc
) as newQueue
from t
) t

在更新语句中:

update t
set queue = newqueue
from (select pkid, eqid, worker, queue,
coalesce(Newqueue, lastone.queue) as newqueue
from (select t.*,
(select top 1 queue from t t2 where t2.pkid < t.pkid order by t2.pkid desc
) as newQueue
from t
) t cross join
(select top 1 queue from t order by pkid desc) as lastone
) newt
where t.pkid = newt.pkid

关于sql - 更新语句以重新排序表队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14063966/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com