简体   繁体   中英

Mysql : left outer join issue

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.

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

Try this OP:

SELECT [gross] = ISNULL(income.income - expenditure.expenditure ,0)
FROM income 
left outer join expenditure on income.month = expenditure.month

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`;

Fiddle demo here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM