【问题标题】:how to get difference of sum of values of acolumn of two different tables in mysql?如何获得mysql中两个不同表的列的值之和的差异?
【发布时间】:2020-04-21 18:29:02
【问题描述】:

餐桌收入

+----+--------+-------------+
| Id | amount | description |
+----+--------+-------------+
| 26 |  10000 | Salary      |
| 27 |    500 | Test        |
+----+--------+-------------+

第二个费用

+----+--------+-------------+
| Id | amount | description |
+----+--------+-------------+
| 10 |   3000 | Rent        |
| 11 |   1500 | Test        |
+----+--------+-------------+

我希望输出为

+-------+
| Total |
+-------+
|  6000 |
+-------+

示例:- 收入总和(金额) - 费用总和(金额);

【问题讨论】:

  • 考虑使用一张表进行交易

标签: mysql sql database group-by subquery


【解决方案1】:

只需减去两个聚合标量查询的结果:

select
    (select sum(amount) from income)
    - (select sum(amount) from expense) total

或者,如果任何表可能为空或仅包含 null 数量:

select
    (select coalesce(sum(amount), 0) from income)
    - (select coalesce(sum(amount), 0) from expense) total

请注意,正如 Strawberry 所评论的,拥有一个收入和支出表可能更适合您的用例。您可以将费用存储为负数,也可以使用一个标志来指示每一行是收入还是费用。

【讨论】:

    猜你喜欢
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多