I made two statements – SUM of revenue and expenses in different tables using group by id (each id has more than one revenue and expenses records):
select id_person, SUM (revenue_d) as sum_revenue from sales group by id_person;
select id_person, SUM (expenses_d) as sum_expenses from expenses group by id_person;
Now I need to subtract expenses.sum_expenses from sales.sum_revenue.
What is a more efficient way to do so?
Using JOINs? Something like that:
SELECT id_person, (sales.sum_revenue - expenses.sum_expenses) as balance FROM sales LEFT OUTER JOIN expenses ON sales.id_person = expenses.id_person;
But how to write all three statements in one?
SELECT id_person, (sales.sum_revenue - expenses.sum_expenses) as balance
FROM (select id_person, SUM (revenue_d) as sum_revenue from sales group by id_person)
LEFT OUTER JOIN
(select id_person, SUM (expenses_d) as sum_expenses from expenses group by id_person)
ON sales.id_person = expenses.id_person;`
2
Answers
There is no need for subqueries.
Assuming the sales has at least as many person_ids as expenses
You can do
First
UNION ALL
, thenGROUP BY
:Or, if you also have a persons table: