我有一个收入和支出表。我想在一个查询中同时选择它们,并获得按月分组的income.amount 字段和expense.amount 字段之间的差异。这样查询将返回一个结果,即基于月份计算的收入总额中的费用总额。我使用了两种方法,但没有奏效。找到以下内容:
SELECT *, count(*), sum(`transaction`.amount) as tiamount, sum(expenditure.amount) as teamount, monthname(`transaction`.date) as mni, monthname(expenditure.date) as mne
FROM `transaction`, expenditure
WHERE month(expenditure.`date`)=month(`transaction`.`date`) and month(`transaction`.`date`)=month(expenditure.`date`)
GROUP BY monthname(`transaction`.date) ORDER BY `transaction`.date Desc
另一个是:
SELECT count(*), `transaction`.date, sum(`transaction`.amount) as tiamount, sum(`transaction`.amount - expenditure.amount) as diff, monthname(`transaction`.date) as mni
FROM `transaction` left join expenditure on monthname(`transaction`.date) = monthname(expenditure.date)
UNION ALL
SELECT count(*), expenditure.date, sum(expenditure.amount) as teamount, sum(`transaction`.amount - expenditure.amount) as diff, monthname(expenditure.date) as mne
FROM expenditure left join `transaction` on monthname(`transaction`.date) = monthname(expenditure.date)
任何帮助,将不胜感激。谢谢。