MySQL query with JOINS and GROUP BY
- by user1854049
I'm building a MySQL query but I can't seem to get it right.
I have four tables:
- customers
- orders
- sales_rates
- purchase_rates
There is a 1:n relation 'customernr' between customers and orders.
There is a 1:n relation 'ordernr' between orders and sales_rates.
There is a 1:n relation 'ordernr' between orders and purchase_rates.
What I would like to do is produce an output of all customers with their total purchase and sales amounts.
So far I have the following query.
SELECT c.customernr, c.customer_name, SUM(sr.sales_price) AS sales_price, SUM(pr.purchase_price) AS purchase_price
FROM orders o, customers c, sales_rates sr, purchase_rates pr
WHERE o.customernr = c.customernr
AND o.ordernr = sr.ordernr
AND o.ordernr = pr.ordernr
GROUP BY k.bedrijfsnaam
The result of the sales_price and purchase_price is far too high. I seem to be getting double counts. What am I doing wrong? Is it possible to perform this in a single query?
Thank for your response!