-1

I have a table like this in mysql where only three field id,credit and debit exists now i want to calculate the current balance as like below in examp column i show how i want mysql to calculate it will search for just previous time current balance. table is ordered by time.....

id  credit  debit   Time                balance  Examp
1   100             1/6/2013 11:11      100 
1           50      1/6/2013 13:14      50      (100-50)
1   20              2/6/2013 10:10      70      (50+20)
2   200             1/6/2013 11:12      200
2   100             1/6/2013 11:14      300     (200 + 100)
2           150     2/6/2013 10:10      150     (300 -150)
peterm
  • 91,357
  • 15
  • 148
  • 157
Shivesh Jaiswal
  • 107
  • 2
  • 3
  • 13

1 Answers1

3

Try

SELECT id, credit, debit, time, balance
FROM
(
  SELECT t.*, @n := IF(@g <> id, 0, @n) + COALESCE(credit,0) - COALESCE(debit, 0) balance, @g := id
    FROM table1 t, (SELECT @n := 0) n, (SELECT @g := 0) g
   ORDER BY id, time
) q

Output:

+------+--------+-------+---------------------+---------+
| id   | credit | debit | time                | balance |
+------+--------+-------+---------------------+---------+
|    1 |    100 |  NULL | 2013-01-06 11:11:00 |     100 |
|    1 |   NULL |    50 | 2013-01-06 13:14:00 |      50 |
|    1 |     20 |  NULL | 2013-02-06 10:10:00 |      70 |
|    2 |    200 |  NULL | 2013-01-06 11:12:00 |     200 |
|    2 |    100 |  NULL | 2013-01-06 11:14:00 |     300 |
|    2 |   NULL |   150 | 2013-02-06 10:10:00 |     150 |
+------+--------+-------+---------------------+---------+

Here is SQLFiddle demo

peterm
  • 91,357
  • 15
  • 148
  • 157