简体   繁体   中英

How to update table based on the values in other columns

Here is a sample below, I want to update AvailableAmt column based on the amount entered on UI.

在此处输入图片说明

Requirement

Update the value from the last row to the first row,

  1. If entered 500 on UI, then the table will be like 在此处输入图片说明

  2. If entered 1000 on UI, then the table will be like 在此处输入图片说明

Thank you for your help in advance !

Can't test it on a Sybase somewhere.
But in theory something like this might work:

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]);

For a Sybase flavor that doesn't support the window function of SUM, something like this might work.

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM