I have two tables such as
- Income(point, date, inc)
- Outcome(point, date, out)
where point and date are the primary key.
I need to find out the total income inc
and outcome out
on any given date.
My answer
WITH all_date AS
(SELECT point, date FROM income
UNION
SELECT point, date FROM outcome)
SELECT a.point, a.date, SUM(inc), SUM(out)
FROM all_date a LEFT JOIN income i ON i.point=a.point AND i.date=d.date
LEFT JOIN outcome o ON o.point=a.point AND o.date=a.date
GROUP BY a.point, a.date
But I am getting wrong result. Because the all_date LEFT JOIN income
while trying to do LEFT JOIN
with outcome
duplicates certain rows from income
, hence messing with the final SUM
.
Basically I want to LEFT JOIN
the third table outcome
with all_date
not with all_date LEFT JOIN income
. Refer to Qus No 30. of http://www.sql-ex.ru/learn_exercises.php for further clarification