SELECT中的总和和小计...结果

时间:2014-03-10 13:03:06

标签: mysql sql

我试图分别得到每个客户订单的总和,但我实际上得到了所有订单的总和。我在这里做错了什么?

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

2 个答案:

答案 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时,即使他们在customersorders中没有任何记录,也会显示表格orderdetails的结果。

试一试!