MySQL查询从Sum中查找余额

时间:2015-02-03 08:00:25

标签: mysql sql

我有一个如下的交易表:

debit_amount         to_be_collect  
5.00                 56.48  
100.00               0.00   
30.00                143.97     

需要将结果作为to_be_collect的总和 - 借记金额,如分类帐帐户。预期结果集如下

  debit_amount       to_be_collect                   balance
  ------------------------------------------------------------------------
  5.00               56.48             195.45(sum of to_be_collect - debit)
  100.00             0.00              95.45 (195.45 - 100)
  30.00              143.97            65.45 (95.45 - 30)

是否可以从查询中获取结果或者我是否使用存储过程?请帮忙。

1 个答案:

答案 0 :(得分:3)

为此使用用户定义的变量。详细了解他们here

示例数据:

CREATE TABLE t
    (id int auto_increment primary key, `debit_amount` numeric(5,2), `to_be_collect` numeric(5,2))
;

INSERT INTO t
    (`debit_amount`, `to_be_collect`)
VALUES
    (5.00, 56.48),
    (100.00, 0.00),
    (30.00, 143.97)
;

查询:

select
t.*,
@balance := @balance - debit_amount as balance
from
t
, (select @balance := sum(to_be_collect) from t) var_init_subquery
order by id

结果:

| ID | DEBIT_AMOUNT | TO_BE_COLLECT | BALANCE |
|----|--------------|---------------|---------|
|  1 |            5 |         56.48 |  195.45 |
|  2 |          100 |             0 |   95.45 |
|  3 |           30 |        143.97 |   65.45 |