mysql - Selecting the difference of sum of a column from one table and sum of a column from another table -
i have 2 tables income , expenses. have calculate sum of expenses , incomes , calculate difference of both sums.
i using
select (sum(a.amount)-(select sum(i.amount) incomes group i.userid)) expense, a.userid amount group a.userid
at present there on userid in income table, when execute query, taking sum of userid's income , subtracting everyone's expenses.
i need individual difference.
you can use subselect
select (q.amount - q.expense) `diff` ( (select (sum(a.amount) amount group a.userid) `amount`, (select sum(i.amount) incomes group i.userid) expense, ) q
or join
select (q.amount - q.expense) `diff` ( select sum(a.amount) `amount` ,sum(i.amount) `expense` amount join incomes on ( a.userid=i.userid) group i.userid ) q
or can try full outer join don't exist still can same using union
select (q.amount - q.expense) `diff` ( (select (sum(a.amount) `amount` , null `expense` amount group a.userid) union (select null `amount`, sum(i.amount) expense incomes group i.userid) ) q
Comments
Post a Comment