Consider this example, which uses a non-temporary table...
Note, my balance differs from yours - but I assume that's because you made a mistake!?!
Source
DROP TABLE IF EXISTS temp;
CREATE TABLE temp
(slno INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,debit INT null
,credit INT null
);
INSERT INTO temp VALUES
(1,10,0),
(2,0,40),
(3,50,0),
(4,0,10),
(5,0,10);
SELECT * FROM temp;
+------+-------+--------+
| slno | debit | credit |
+------+-------+--------+
| 1 | 10 | 0 |
| 2 | 0 | 40 |
| 3 | 50 | 0 |
| 4 | 0 | 10 |
| 5 | 0 | 10 |
+------+-------+--------+
SELECT x.slno
, x.debit
, x.credit
, SUM(y.bal) balance
FROM
(
SELECT *,debit-credit bal FROM temp
) x
JOIN
(
SELECT *,debit-credit bal FROM temp
) y
ON y.slno <= x.slno
GROUP
BY x.slno;
+------+-------+--------+---------+
| slno | debit | credit | balance |
+------+-------+--------+---------+
| 1 | 10 | 0 | 10 |
| 2 | 0 | 40 | -30 |
| 3 | 50 | 0 | 20 |
| 4 | 0 | 10 | 10 |
| 5 | 0 | 10 | 0 |
+------+-------+--------+---------+
Note, my balance differs from yours - but I assume that's because you made a mistake!?!
Source