如何根据其他列中的值更新 table

How to update table based on the values in other columns

下面是一个示例,我想根据 UI 上输入的金额更新 AvailableAmt 列。

要求

将最后一行的值更新到第一行,

  1. 如果在 UI 上输入 500,那么 table 会像

  2. 如果在 UI 上输入 1000,那么 table 会像

提前感谢您的帮助!

无法在某处的 Sybase 上测试它。
但理论上这样的事情可能会起作用:

DECLARE @Group VARCHAR(8) = 'a';
DECLARE @Amount INT = 1100;

UPDATE t
SET t.AvailableAmt = 
  CASE 
  WHEN q.PrevRemain > 0 AND t.AvailableAmt <= q.PrevRemain THEN 0
  WHEN q.PrevRemain > 0 THEN t.AvailableAmt - q.PrevRemain
  ELSE t.AvailableAmt
  END
FROM YourTable t
JOIN
(
    select [Group], [Row], 
     @Amount-(SUM(AvailableAmt) OVER (PARTITION BY [Group] ORDER BY AvailableAmt, [Row] desc) - AvailableAmt) as PrevRemain
    from YourTable
    where AvailableAmt > 0
      and [Group] = @Group
) AS q
ON (q.[Group] = t.[Group] and q.[Row] = t.[Row]);

对于不支持 SUM 的 window 函数的 Sybase 风格,类似这样的方法可能有效。

DECLARE @Group VARCHAR(8) = 'a';
DECLARE @Amount INT = 1200;

UPDATE t
SET t.AvailableAmt = 
  CASE 
  WHEN q.PrevRemain > 0 AND t.AvailableAmt <= q.PrevRemain THEN 0
  WHEN q.PrevRemain > 0 THEN t.AvailableAmt - q.PrevRemain
  ELSE t.AvailableAmt
  END
FROM YourTable t
JOIN
(
    select t1.[Group], t1.[Row], 
     @Amount - (SUM(t2.AvailableAmt)-t1.AvailableAmt) as PrevRemain
    from YourTable t1
    left join YourTable t2 on (t2.[Group] = t1.[Group]  and t2.AvailableAmt <= t1.AvailableAmt and t2.[Row] >= t1.[Row])
    where t1.AvailableAmt > 0
      and t1.[Group] = @Group
    group by t1.[Group], t1.[Row], t1.AvailableAmt
) AS q 
ON (q.[Group] = t.[Group] and q.[Row] = t.[Row]);