如何保持交易的运行余额并获得交易后的金额

时间:2014-12-07 06:46:43

标签: mysql

我必须编写一个查询,该查询使用变量列出按日期排序的所有交易,由客户使用ID 1执行。变量应保持运行余额,以显示每笔交易后客户的新余额。最终输出应该给出交易后的日期,交易金额和当前余额。

表格

+--------------+------------------+------+-----+-------------------+-----------------------------+
| Field        | Type             | Null | Key | Default           | Extra                       |
+--------------+------------------+------+-----+-------------------+-----------------------------+
| customer_id  | int(10) unsigned | YES  | MUL | NULL              |                             |
| last_created | timestamp        | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
| amount       | decimal(6,2)     | NO   |     | NULL              |                             |
+--------------+------------------+------+-----+-------------------+-----------------------------+

查询

SELECT last_created, amount , sum(amount) as moneyspent FROM transactions where 
customer_id = 1   ORDER BY  last_created;

1 个答案:

答案 0 :(得分:1)

SET @total = 0; 
SELECT last_transaction, amount ,@total := @total + amount AS runningtotal 
FROM sakila_payment 
ORDER BY last_transaction;