MySQL query with JOINS and GROUP BY
Posted
by
user1854049
on Stack Overflow
See other posts from Stack Overflow
or by user1854049
Published on 2012-11-26T17:01:45Z
Indexed on
2012/11/26
17:03 UTC
Read the original article
Hit count: 136
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!
© Stack Overflow or respective owner