I use this SQL statement to be able to join three tables (Order1, Order2, and Customers) to show the order quantity for each customer from each city they're addressed to. But how can I show the rows of order quantities for customers in cities who have done at least three orders? In other words I'm trying to aggregate on the cities connected to the customers who have done more than three orders.
Table structures:
Customers
has the columns CustomerNr, City Name
Ordernr, CustomerNr
Order2
has the columns Ordernr, Order quantity
The SQL statement so far:
SELECT
Customers.CityName, Order2.OrderQuantity
FROM
Order1
INNER JOIN
Order2 ON Order1.ordernr = Order2.ordernr
INNER JOIN
Customers ON Customers.CustomerNr = Order1.CustomerNr
What you're missing are aggregate functions. To get the sum of a column, you can use SUM(columnName)
in your select statement. To get proper results, you will have to group by a field as well. In this case, you want the sum per customer so you can do something like this:
SELECT c.customerNumber, c.name, SUM(o2.quantity) AS totalQuantity
FROM customers c
JOIN order1 o1 ON o1.customerNumber = c.customerNumber
JOIN order2 o2 ON o2.orderNumber = o1.orderNumber
GROUP BY c.customerNumber, c.name;
To filter on an aggregate condition, you need to add a having clause. Here, you can require that each group have a minimum of 3 rows:
SELECT c.customerNumber, c.name, SUM(o2.quantity) AS totalQuantity
FROM customers c
JOIN order1 o1 ON o1.customerNumber = c.customerNumber
JOIN order2 o2 ON o2.orderNumber = o1.orderNumber
GROUP BY c.customerNumber, c.name
HAVING COUNT(*) >= 3;
Here is an SQL Fiddle with some dummy data that I tested with.
select c.CityName, Sum(o2.OrderQuantity) as Quantity
from Customers c
inner join Order1 o1 on c.CustomerNr = o1.CustomerNr
inner join Order2 o2 on o1.OrderNr = o2.OrderNr
group by c.CityName
having sum(o2.OrderQuantity) >= 3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.