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