如何连接三个表,其中一个表与其他两个表的ID不匹配?

时间:2014-12-07 18:41:20

标签: sql sql-server join sum aggregate

我试图找出如何使用正确的SQL语句解决这个问题: "在客户至少订购了三个订单的城市中,向所有客户销售了多少。结果应显示这些客户的城市名称和总订单数量"。

问题是我有三个表可供使用:Order1,Order2和Customers。这些表的结构如下所示:

Order1 has the attributes: Ordernr, CustomerNr.
Order2 has the attributes: Ordernr, Order quantity.
Customers has the attributes: CustomerNr, Customer name, City name.

使用此代码,我可以加入三个表格,以便显示每个城市的每个客户的订单数量。但是,如何在至少有三个订单的城市中显示客户的订单数量?

SELECT Customers.CustomerNr, CityName, Order2.OrderQuantity
FROM Order1 INNER JOIN Order2
   ON Order1.ordernr = Order2.ordernr JOIN Customers
   ON Customers.CustomerNr = Order1.CustomerNr

2 个答案:

答案 0 :(得分:0)

此查询将返回至少包含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

现在您想要来自这些城市的客户的所有订单(我想从表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
 )

希望这有帮助

答案 1 :(得分:0)

试试这个:

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