我试图分别得到每个客户订单的总和,但我实际上得到了所有订单的总和。我在这里做错了什么?
SELECT c.customerNumber, sum( r.quantityOrdered * r.priceEach ) AS sum
FROM customers c, orders o, orderdetails r
WHERE c.customerNumber = o.customerNumber
AND o.orderNumber = r.orderNUmber
GROUP BY c.customerNumber
HAVING COUNT( o.orderNumber ) <=3
答案 0 :(得分:0)
除了HAVING
子句之外,您的查询对我来说没问题。我不知道你真正想用HAVING COUNT( o.orderNumber ) <=3
实现什么。您真的想要订购3或更少的客户吗?你尝试过使用过:
SELECT c.customerNumber, sum(r.quantityOrdered * r.priceEach) AS sum
FROM customers c
INNER JOIN orders o ON c.customerNumber = o.customerNumber
INNER JOIN orderdetails r ON o.orderNumber = r.orderNUmber
GROUP BY c.customerNumber
答案 1 :(得分:0)
首先,您应该使用JOIN
,因为这是编写语法的标准方法。使阅读更容易。
SELECT c.customerNumber, sum( r.quantityOrdered * r.priceEach ) AS sum
FROM customers c
LEFT JOIN orders o ON c.customerNumber = o.customerNumber
LEFT JOIN orderdetails r ON o.orderNumber = r.orderNUmber
GROUP BY c.customerNumber
HAVING COUNT( o.orderNumber ) <=3
当您使用LEFT JOIN
时,即使他们在customers
和orders
中没有任何记录,也会显示表格orderdetails
的结果。
试一试!