Showing posts with label balance calculation. Show all posts
Showing posts with label balance calculation. Show all posts

Saturday, December 15, 2018

how to calculate balance with previous value.

Consider this example, which uses a non-temporary table... 
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