如何基于其他列中的值更新表

时间:2018-12-26 15:25:18

标签: sql sybase

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

enter image description here

要求

将值从最后一行更新到第一行

  1. 如果在用户界面上输入500,则表格将类似于 enter image description here

  2. 如果在用户界面上输入1000,则表格将类似于 enter image description here

谢谢您的帮助!

1 个答案:

答案 0 :(得分:1)

无法在某个地方的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窗口功能的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]);