我必须表:
收入:
| date | incomeAmount |
花费:
| date | expenseAmount |
我想使用以下方法总结我在特定月份的所有收入:MONTH(date) = ?
我还需要总结我在同一个月的所有费用
然后减去得到我当月的利润,输出表类似于:
| Month | TotalIncomes | TotalExpenses | Profit |
我怎样才能创建一个 SQL 查询来做到这一点?谢谢大家的帮助!
我必须表:
收入:
| date | incomeAmount |
花费:
| date | expenseAmount |
我想使用以下方法总结我在特定月份的所有收入:MONTH(date) = ?
我还需要总结我在同一个月的所有费用
然后减去得到我当月的利润,输出表类似于:
| Month | TotalIncomes | TotalExpenses | Profit |
我怎样才能创建一个 SQL 查询来做到这一点?谢谢大家的帮助!
您可以加入聚合表。
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
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
;