[英]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 但我不知道该怎么做http://sqlfiddle.com/#!9/7a7d5/1
If someone can help on this sqlfiddle 如果有人可以帮助这个sqlfiddle
Thanks. 谢谢。
I assume that if there is no income then this should be treated as 0, likewise for expenditure. 我假设如果没有收入,则应将其视为0,同样用于支出。
MySQL doesn't have a full outer join but you can do something similar: MySQL没有完整的外部联接,但是您可以执行类似的操作:
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 示例: 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`;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.