2014-12-07 75 views
1

我必须编写一个查询,该查询使用变量列出由客户使用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
SET @total = 0; 
SELECT last_transaction, amount ,@total := @total + amount AS runningtotal 
FROM sakila_payment 
ORDER BY last_transaction; 
相关问题