【问题标题】:How to keep a running balance of transactions and get the amount after the transactions如何保持交易的运行余额并获得交易后的金额
【发布时间】:2014-12-07 06:46:43
【问题描述】:

我必须编写一个查询,该查询使用一个变量列出所有交易,按日期排序,由 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;

【问题讨论】:

    标签: mysql


    【解决方案1】:
    SET @total = 0; 
    SELECT last_transaction, amount ,@total := @total + amount AS runningtotal 
    FROM sakila_payment 
    ORDER BY last_transaction;
    

    【讨论】:

      猜你喜欢
      • 2020-11-15
      • 2015-11-09
      • 2022-01-11
      • 2020-07-10
      • 2019-03-28
      • 2013-10-21
      • 2016-03-24
      • 1970-01-01
      • 2021-10-11
      相关资源
      最近更新 更多