[英]How do a join three tables where one table doesn't match the ID of the other two?
I'm trying to figure out how to solve this question with a proper SQL statement: "How much has been sold to all customers in cities where a customer has made at least three orders. The result should display the city name and the total order quantity for these customers". 我正在尝试通过适当的SQL语句来解决该问题:“在一个客户已至少下达三笔订单的城市中,已售出了多少钱给所有客户。结果应显示城市名称和总订单这些客户的数量”。
The thing is that I have three tables to work with: Order1, Order2, and Customers. 问题是我有三个表可以使用:Order1,Order2和Customers。 The table structures for these look like this: 这些表格的结构如下:
Order1 has the attributes: Ordernr, CustomerNr.
Order2 has the attributes: Ordernr, Order quantity.
Customers has the attributes: CustomerNr, Customer name, City name.
With this code I can join the three tables to be able to show the order quantity for each customer from each city. 使用此代码,我可以将三个表连接起来,以显示每个城市的每个客户的订单数量。 But how can I show the order quantity for customers in cities who've at least three orders? 但是,如何为至少有三个订单的城市中的客户显示订单数量?
SELECT Customers.CustomerNr, CityName, Order2.OrderQuantity
FROM Order1 INNER JOIN Order2
ON Order1.ordernr = Order2.ordernr JOIN Customers
ON Customers.CustomerNr = Order1.CustomerNr
This query will return a list of cities with at least 3 orders: 此查询将返回至少3个订单的城市列表:
select CityName
from Customers c
join Order1 o1 on c.CustomerNr = o1.CustomerNr
join Order2 o2 on o1.OrderNr = o2.OrderNr
group by c.CityName having Sum(o2.OrderQuantity) > 3
Now you want all orders (I suppose from table Order1
) from customers from these cities 现在,您需要来自这些城市的客户的所有订单(我想从表Order1
)
select o1.*
from Order1 o1 joib Customer c on c.CustomerNr = o.CustomerNr
where c.CityName in (
select CityName
from Customers c
join Order1 o1 on c.CustomerNr = o1.CustomerNr
join Order2 o2 on o1.OrderNr = o2.OrderNr
group by c.CityName having Sum(o2.OrderQuantity) > 3
)
Hope this helps 希望这可以帮助
Try this: 尝试这个:
SELECT c.CityName, SUM(o2.OrderQuantity) OrderQuantity
FROM Order1 o1
INNER JOIN (SELECT o1.CustomerNr
FROM Order1 o1
GROUP BY o1.CustomerNr
HAVING COUNT(o1.Ordernr) >= 3
) AS a ON o1.CustomerNr = a.CustomerNr
INNER JOIN Order2 o2 ON o1.Ordernr = o2.Ordernr
INNER JOIN Customers c ON o1.CustomerNr = c.CustomerNr
GROUP BY c.CityName
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.