我可以在GROUP BY之前执行COUNT()

时间:2012-10-11 21:40:58

标签: mysql sql count mysql-workbench

我正在为学校做mySQL任务,我遇到了一个问题。我还是mySQL的新手。 COUNT(o.customer_id)没有按照我想要的方式工作。我想要它计算订单数量,但它计算所有项目。即客户1有2个订单,但它返回3,因为一个订单有两个项目。我有三个表与客户,另一个与订单而不是每个订单上的每个项目。我在下面提出了我的问题。任何帮助都会很棒。

SELECT email_address, COUNT(o.order_id) AS num_of_orders,
       SUM(((item_price - discount_amount) * quantity)) AS total
FROM customers c JOIN orders o
      ON c.customer_id = o.customer_id
     JOIN order_items ot
      ON o.order_id = ot.order_id
GROUP BY o.customer_id
HAVING num_of_orders > 1
ORDER BY total DESC;

3 个答案:

答案 0 :(得分:4)

就像使用Distinct保留字一样简单:

SELECT email_address, COUNT(distinct o.order_id) AS num_of_orders

答案 1 :(得分:2)

看起来您想要计算DISTINCT订单数量。将DISTINCT添加到COUNT中。虽然MySQL允许你在HAVING子句中使用SELECT表达式,但这样做并不好。

SELECT email_address, COUNT(DISTINCT o.order_id) AS num_of_orders,
       SUM(((item_price - discount_amount) * quantity)) AS total
FROM customers c JOIN orders o
      ON c.customer_id = o.customer_id
     JOIN order_items ot
      ON o.order_id = ot.order_id
GROUP BY o.customer_id
HAVING COUNT(DISTINCT o.order_id) > 1
ORDER BY total DESC;

答案 2 :(得分:-1)

只需将联接取出即可。当有多个项目时,它所做的只是重复行。

SELECT email_address, COUNT(o.order_id) AS num_of_orders,
       SUM(((item_price - discount_amount) * quantity)) AS total
FROM customers c JOIN orders o
      ON c.customer_id = o.customer_id
GROUP BY o.customer_id
HAVING COUNT(o.order_id) > 1
ORDER BY total DESC;