Update the total based on the previous row of balance

后端 未结 4 2065
难免孤独
难免孤独 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:47

    SET @prev_id = 1;
    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 
      (SELECT Balance FROM tableName WHERE id = @prev_id) + (Col1 + Col2)
      WHEN Col3 = B and Col4 <> Z THEN 
      (SELECT Balance FROM tableName WHERE id = @prev_id) + (Col1 - Col2)
      WHEN Col3 = C and Col4 <> Z THEN 
      (SELECT Balance FROM tableName WHERE id = @prev_id) + (Col1 * Col2)
    END,
    @prev_id := id
    
    WHERE t1.id > 1;
    

提交回复
热议问题