I am an SQL newbie, sorry if the answer is obvious. Note that I have researched and tried to solve this for some 2h now. Please read carefully before considering this question redundant.
I would like to join three tables, one of which needs to be a full join, and then SELECT and GROUP BY on the result, such as here:
SELECT country, COUNT(DISTINCT customerNumber), SUM(priceEach*quantityOrdered)
FROM orders
LEFT JOIN orderdetails USING (orderNumber)
FULL JOIN customers USING (customerNumber)
GROUP BY country;
Full joins are done with the UNION of a left and right join. Using SELECT and GROUP BY to calculate fields based on LEFT-RIGHT-JOIN-UNION and LEFT JOIN caused data to end up in the wrong columns in the final ouput. This did not work:
SELECT country, COUNT(DISTINCT customerNumber), SUM(priceEach*quantityOrdered)
FROM (SELECT * FROM orders LEFT JOIN customers USING(customerNumber)
UNION
SELECT * FROM orders RIGHT JOIN customers USING(customerNumber)) as ocFull
LEFT JOIN orderdetails USING (orderNumber)
GROUP BY country;
I cannot figure out my error. What am I doing wrong? Alternatively, how is this usually done? Please help!