Reputation: 3429
I have two tables :
income(month, amount)
expenditure(month, amount)
I need to display for each month of table income its amount minus expenditure amount (if it exists).
I think I need to use a left outer join between the two tables, something like
SELECT income.amount - expenditure.amount
FROM income left outer join expenditure on income.month = expenditure.month
but I don't know how to do that http://sqlfiddle.com/#!9/7a7d5/1
If someone can help on this sqlfiddle
Thanks.
Upvotes: 0
Views: 44
Reputation: 11556
Query
select t1.`month`,
coalesce((t1.`income`-t2.`expenditure`),t1.`income`) as Savings
from `income` t1
left join `expenditure` t2
on t1.`month`=t2.`month`
order by t1.`month`;
Upvotes: 0
Reputation: 22656
I assume that if there is no income then this should be treated as 0, likewise for expenditure.
MySQL doesn't have a full outer join but you can do something similar:
SELECT month, SUM(amount) FROM
(SELECT month, income AS amount
FROM income
UNION
SELECT month, - expenditure AS amount
FROM expenditure) a
GROUP BY month;
This creates a union of the two tables (with expenditure as a negative for simplicity). It then simply sums the amounts and groups by month.
Example: http://sqlfiddle.com/#!9/7a7d5/14
Upvotes: 1
Reputation: 703
Try this OP:
SELECT [gross] = ISNULL(income.income - expenditure.expenditure ,0)
FROM income
left outer join expenditure on income.month = expenditure.month
Upvotes: 0