3

我正在为学校做一个 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;
4

3 回答 3

6

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

SELECT email_address, COUNT(distinct o.order_id) AS num_of_orders
于 2012-10-11T21:44:51.653 回答
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;
于 2012-10-11T21:42:17.893 回答
-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;
于 2012-10-11T21:51:04.190 回答