如何显示相对于城市客户至少有三个订单的城市的订单数量?

时间:2014-12-07 20:16:40

标签: sql sql-server aggregate

我使用此SQL语句可以连接三个表(Order1,Order2和Customers),以显示他们所处理的每个城市的每个客户的订单数量。但是,如何为已完成至少三个订单的城市的客户显示订单数量的行?换句话说,我试图在连接到已完成三个以上订单的客户的城市进行汇总。

表格结构:

  • Customers包含CustomerNr, City Name
  • 订单1 的列为Ordernr, CustomerNr
  • Order2包含Ordernr, Order quantity

到目前为止的SQL语句:

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

2 个答案:

答案 0 :(得分:0)

您缺少的是聚合函数。要获取列的总和,可以在select语句中使用SUM(columnName)。要获得正确的结果,您还必须按字段分组。在这种情况下,您需要每个客户的总和,以便您可以执行以下操作:

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子句。在这里,您可以要求每个组至少有3行:

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;

这是一个SQL Fiddle,其中包含我测试过的一些虚拟数据。

答案 1 :(得分:0)

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