从多个表到一个查询的多个SUM

时间:2015-07-30 17:13:39

标签: php mysql web

我有两张桌子:incomes& outgo都包含有关交易的信息。我想运行一份报告,根据表格中的总数显示整体资金流量,我目前通过使用以下查询手动执行此操作:

1) SELECT amount, SUM(amount) AS intotal FROM incomes
2) SELECT amount, SUM(amount) AS outtotal FROM outgo

例如,假设intotal500outtotal300

我想要一个查询来获取摘要,并从outtotal金额减去intotal金额,在这种情况下结果为200。任何人都可以指出我正确的方向或帮助我的语法?

2 个答案:

答案 0 :(得分:1)

这个怎么样:

SELECT
   (SELECT SUM(amount) FROM incomes)
   -
   (SELECT SUM(amount) FROM outgo)

答案 1 :(得分:1)

尝试

SELECT
    (SELECT amount, SUM(amount) AS intotal FROM incomes) AS a,
    (SELECT amount, SUM(id) AS outtotal FROM outgo) AS b

a.intotalb.outtotal

一起使用

或直接使用

SELECT 
    ((SELECT SUM(amount)FROM incomes) - (SELECT SUM(amount)FROM outgo)) AS total