i’m new here as I’m learning SQL and I’ve encountered a problem I can’t solve. Please help me.
I have two tables Outcome and Income with data, see screenshot of the tables.
https://www.box.com/s/5c1ah5qi9jg5ty499wvs
I want to join these tables but due to carthesian product some of the data is being added two times. Here is my code:
select o.point, o.date, sum(out), sum(inc) from outcome o left join income i on o.point=i.point and o.date=i.date
group by o.point, o.date
union
select i.point, i.date, sum(out), sum(inc) from income i left join outcome o on o.point=i.point and o.date=i.date
group by i.point, i.date
Any advice? Thanks in advance.
G.
I think what you want is a
full outer joinrather than aunion:Alternatively, you might want to do a
unionbetween the two tables, and then aggregate, as in:This version will work correctly, even if there are multiple rows in each table for a given point/date combination.