lundi 11 juillet 2016

How to sum a value in a joined table only once

I have two tables ID CUST ORDER ============= 1 1 1 2 1 1 3 1 1 ID CUST PARTS1 PARTS2 ===================== 1 1 5 3 What I want in returns is CUST ORDERS PARTS ================= 1 3 8 The select that I'm currently using is SELECT Distinct(o.cust), orders=sum(order), parts=sum(p.parts1 + p.parts2) FROM orders as o left join parts p on o.cust = p.cust GROUP BY o.cust The problem is the parts are summed for every row in the order table for that customer. Instead of 8 parts I get 24 (3*8) How can I come up with the correct value for parts? UPDATE: I want all of the rows in the first table. So I want to see all of the orders even when the customer doesn't have any parts in the second table.

Aucun commentaire:

Enregistrer un commentaire