Update the total based on the previous row of balance

后端 未结 4 2068
难免孤独
难免孤独 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 14:00

    UPDATE tableName t1 SET 
    Total =  
    CASE
      WHEN t1.Col3 = "A" and t1.Col4 <> "Z" THEN t1.Col1 + t1.Col2
      WHEN t1.Col3 = "B" and t1.Col4 <> "Z" THEN t1.Col1 - t1.Col2
      WHEN t1.Col3 = "C" and t1.Col4 <> "Z" THEN t1.Col1 * t1.Col2
    END
    Balance = 
    CASE
      WHEN t1.Col3 = "A" and t1.Col4 <> "Z" THEN 
      (SELECT t2.Balance FROM tableName t2 
        WHERE t2.id = (select max(t3.id) from tableName t3 where t3.id < t1.id))
        + (t1.Col1 + t1.Col2)
      WHEN t1.Col3 = "B" and t1.Col4 <> "Z" THEN 
      (SELECT t2.Balance FROM tableName t2 
        WHERE t2.id = (select max(t3.id) from tableName t3 where t3.id < t1.id))
        + (t1.Col1 - t1.Col2)
      WHEN t1.Col3 = "C" and t1.Col4 <> "Z" THEN 
      (SELECT t2.Balance FROM tableName t2 
        WHERE t2.id = (select max(t3.id) from tableName t3 where t3.id < t1.id))
        + (t1.Col1 * t1.Col2)
    END
    WHERE t1.id > 1;
    

提交回复
热议问题