如果您的 RDMS 支持 LAG,您可以像这样使用它
WITH new_order
AS (SELECT rec_no,
COALESCE(Lag(order_no) OVER ( ORDER BY order_no), --Previous value
Max(order_no) OVER ( ORDER BY order_no DESC)) --Max Value when no previous
NEW_ORDER_NO
FROM rotation_list)
UPDATE rotation_list
SET order_no = new_order.new_order_no
FROM rotation_list
INNER JOIN new_order
ON rotation_list.rec_no = new_order.rec_no
演示
如果您的 RDMS 支持 ROW_NUMBER 但不支持 LAG() (查看您的 sql 2008),您可以执行此操作
WITH cte
AS (SELECT rec_no,
order_no,
Row_number() OVER ( ORDER BY order_no) rn
FROM rotation_list),
new_order
AS (SELECT no.rec_no,
COALESCE(no_prev.order_no,
Max(no.order_no) OVER (partition BY NULL )) new_order_no
FROM cte no
LEFT JOIN cte no_prev
ON no.rn - 1 = no_prev.rn)
UPDATE rotation_list
SET order_no = new_order.new_order_no
FROM rotation_list
INNER JOIN new_order
ON rotation_list.rec_no = new_order.rec_no;
演示