Imrul.H
Imrul.H

Reputation: 5870

mysql select data with calculation between 2 tables and group by month

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?

Upvotes: 2

Views: 1088

Answers (1)

Eric
Eric

Reputation: 95133

What you want is a union with some date magic for the aggregate:

select
    date_format(x.date, '%M %Y') as `month`,
    sum(amount) as profit
from
    (select amount, date
     from income
     union all
     select amount*-1 as amount, date
     from expense
    ) x
group by
    date_format(x.date, '%M %Y')

The specific thing we're using here is date_format to get the dates the way we want it. Also, we're multiplying amount by -1 when it comes from expense to make the calculation correct. Of course, we could have returned different columns for income and expense and then did the math on them in the sum, such as sum(x.income_amount, x.expense_amount), but there's no need to do that when you can just quickly do a *-1 to the column on before it hits the sum.

The other important thing is the group by. Here, we're grouping by a function that formats the date as Month, YYYY, so it will get the divisions you're looking for.

Upvotes: 4

Related Questions