Update the total based on the previous row of balance

后端 未结 4 2069
难免孤独
难免孤独 2021-01-22 13:05

This is the database data.

Name   id  Col1  Col2  Col3 Col4 Total  Balance
Row1   1    6     1     A     Z     -      - 
Row2   2    2     3     B     Z     -            


        
4条回答
  •  心在旅途
    2021-01-22 13:40

    Try This

     SET @old_balance = 0;
        UPDATE tableName SET 
        Total =  
        CASE
          WHEN Col3 = 'A' and Col4 <> 'Z' THEN Col1 + Col2
          WHEN Col3 = 'B' and Col4 <> 'Z' THEN Col1 - Col2
          WHEN Col3 = 'C' and Col4 <> 'Z' THEN Col1 * Col2
        END,
        Balance = 
        CASE
          WHEN Col3 = 'A' and Col4 <> 'Z' THEN 
          @old_balance + (Col1 + Col2)
          WHEN Col3 = 'B' and Col4 <> 'Z' THEN 
          @old_balance + (Col1 - Col2)
          WHEN Col3 = 'C' and Col4 <> 'Z' THEN 
          @old_balance + (Col1 * Col2)
        END,
        @old_balance := 
        CASE
          WHEN Col3 = 'A' and Col4 <> 'Z' THEN 
          @old_balance + (Col1 + Col2)
          WHEN Col3 = 'B' and Col4 <> 'Z' THEN 
          @old_balance + (Col1 - Col2)
          WHEN Col3 = 'C' and Col4 <> 'Z' THEN 
          @old_balance + (Col1 * Col2)
        END
        WHERE t1.id > 1;
    

提交回复
热议问题