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