2014-12-07 117 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; 
相關問題