如何计算每组的运行总量(余额)

时间:2013-06-28 07:31:35

标签: php mysql

我在mysql中有一个这样的表,其中只有三个字段ID,信用卡和借记卡现在我想要计算当前余额,如下面的示例列中所示我希望mysql如何计算它将只搜索上一次目前的平衡。表按时间排序.....

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)

1 个答案:

答案 0 :(得分:3)

尝试

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

输出:

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

这是 SQLFiddle 演示