查询计算一个月的利润

时间:2016-10-02 21:13:30

标签: sql database libreoffice-base

我需要表格:

收入:

| date | incomeAmount |

开支:

| date | expenseAmount |

我想在一个特定月份汇总我所有的收入:MONTH(date)=?

我还需要在同一个月累计所有费用

然后减去以获得当月的利润,输出表类似于:

| Month | TotalIncomes | TotalExpenses | Profit |

如何创建SQL查询才能执行此操作? 谢谢你的帮助!

2 个答案:

答案 0 :(得分:0)

SELECT I.Month AS Month,
       I.TotalIncomes AS TotalIncomes,
       E.TotalExpenses AS TotalExpenses,
       I.TotalIncomes - E.TotalExpenses AS Profit
  FROM ( SELECT EXTRACT(MONTH FROM DATE ) AS Month,
                SUM( I.incomeAmount ) AS TotalIncomes
           FROM Incomes
       )  I,
       (
         SELECT EXTRACT(MONTH FROM DATE ) AS Month,
                SUM( E.expenseAmount ) AS TotalExpenses
           FROM Expenses
       ) E
 WHERE I.Month = E.Month
;

答案 1 :(得分:0)

您可以加入汇总表格。

SELECT A.Month, TotalIncomes, TotalExpenses, TotalIncomes-TotalExpenses AS Profit
FROM (MONTH(Date) AS Month, SUM(incomeAmount) AS TotalIncomes
      FROM Incomes 
      GROUP BY MONTH(Date)
      ) A 
INNER JOIN (
      MONTH(Date) AS Month, SUM(expenseAmount) AS TotalExpenses
      FROM Incomes 
      GROUP BY MONTH(Date)
      ) B
 ON A.Month = B.Month