从借方和贷方表计算账户余额

时间:2018-03-04 21:11:24

标签: mysql sql database join sum

我有一个像这样的帐户表

+-----------+--------------+
|     fld_id|         name |
+-----------+--------------+
|         1 |         Bank1|
|         2 |         Bank2|
|         4 |         Bank3|
+-----------+--------------+

收入收入表就像这样

+-----------+--------------+---------------+-------------+
| fld_id    | fld_type     | fld_account id| fld_amount  |
+-----------+--------------+---------------+-------------+
|         1 |         Salry|            1  |     400     |
|         2 |         Rent |            2  |     500     |
|         4 |       Others |            1  |    1000     |
+-----------+--------------+---------------+-------------+

付款表赞这个

+-----------+--------------+---------------+-------------+
| fld_id    | fld_type     | fld_account id| fld_amount  |
+-----------+--------------+---------------+-------------+
|         1 |         Food |            2  |     200     |
|         2 |    Entertain |            2  |     300     |
|         4 |    Transport |            1  |     400     |
+-----------+--------------+---------------+-------------+

我想要一个帐户的最终余额表,其中收入,费用和余额的总和如此表 -

+-----------+--------------+---------------+-------------+
| account   | Income       | Expence       | Balance     |
+-----------+--------------+---------------+-------------+
|     Bank1 |         1400 |          400  |    1000     |
|     Bank2 |          500 |          500  |       0     |
|     Bank3 |            0 |            0  |       0     |
+-----------+--------------+---------------+-------------+

到目前为止,我编写此查询并获得收入和费用但未找到任何计算余额的方法,我的查询和结果是--query

SELECT fld_account as account, Income, Expense
from tbl_accounts
LEFT JOIN (SELECT fld_account_id, SUM(fld_amount) as Income FROM tbl_revenue tr GROUP BY tr.fld_account_id) tc on fld_id=tc.fld_account_id
left JOIN (SELECT fld_account_id, SUM(fld_amount) as Expense FROM tbl_payment tp GROUP BY tp.fld_account_id) td on fld_id=td.fld_account_id

,结果如下 -

+-----------+--------------+---------------+
| account   | Income       |   Expense     | 
+-----------+--------------+---------------+
|     Bank1 |         1400 |         400   |
|     Bank2 |          500 |         500   |
|     Bank3 |         Null |         Null  |
+-----------+--------------+---------------+

如何计算余额表格付款和收入表格并将其加入我的帐户表格?非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

只需使用coalesce()

SELECT fld_account as account, COALESCE(Income, 0) as Income,
       COALESCE(Expense, 0) as Expense,
       ( COALESCE(Income, 0) - COALESCE(Expense, 0) ) as balance
FROM tbl_accounts LEFT JOIN
     (SELECT fld_account_id, SUM(fld_amount) as Income
      FROM tbl_revenue tr
      GROUP BY tr.fld_account_id
     ) tc 
     ON fld_id = tc.fld_account_id LEFT JOIN
     (SELECT fld_account_id, SUM(fld_amount) as Expense
      FROM tbl_payment tp
      GROUP BY tp.fld_account_id
     ) td 
     ON fld_id = td.fld_account_id;

COALESCE()是ANSI标准函数,它返回第一个非NULL参数。