I have 2 mysql tables like bellow:
Table income Table expense
id amount date id amount date
1 200 2011-12-10 1 100 2011-12-21
2 300 2011-12-14 2 150 2012-01-01
3 500 2012-01-05 2 200 2012-01-03
I want to get data in this way:
month profit
december, 2011 400
january, 2012 150
Is this possible in a single query?
What you want is a union with some date magic for the aggregate:
The specific thing we’re using here is
date_formatto get the dates the way we want it. Also, we’re multiplyingamountby-1when it comes fromexpenseto make the calculation correct. Of course, we could have returned different columns forincomeandexpenseand then did the math on them in the sum, such assum(x.income_amount, x.expense_amount), but there’s no need to do that when you can just quickly do a*-1to the column on before it hits thesum.The other important thing is the
group by. Here, we’re grouping by a function that formats the date asMonth, YYYY, so it will get the divisions you’re looking for.