3

我有 2 张桌子:

1.customer (contains customers)
2.customer_order (contains orders)

我想知道这个:

no. of customers with 0 orders
no. of customers with 1 order
no. of customers with 2 orders
etc

我有这个:

SELECT COUNT(co.id)
FROM customer c
LEFT JOIN customer_order co
ON c.id=co.id_customer
GROUP BY ??? ;
4

4 回答 4

3

这给出了每个客户的订单数量

SELECT co.id Customer, COUNT(*) Orders
FROM customer_order co  
GROUP BY co.id_customer;

现在使用它作为一个表,并查询它

SELECT Orders, COUNT(*)
FROM (
  SELECT co.id Customer, COUNT(*) Orders
  FROM customer_order co  
  GROUP BY co.id_customer;
)
GROUP BY Orders
于 2013-09-19T13:08:59.973 回答
1

您需要一个子查询,例如:

SELECT cnt, count(*) FROM (SELECT c.id, count(*) cnt FROM customer c 
                      LEFT JOIN customer_order co ON c.id=co.id_customer 
                      GROUP BY c.id) GROUP BY cnt
于 2013-09-19T13:09:02.017 回答
1

尝试:

SELECT count(*), order_count
FROM (
  SELECT c.id, count(*) AS order_count
  FROM customer c, customer_order co
  WHERE c.id = co.id_customer
  GROUP BY c.id
) as A
GROUP BY order_count

这是一个带有工作查询和测试数据的 SQL Fiddle 。

于 2013-09-19T13:09:06.483 回答
0

您应该必须按顺序分组,以便获得编号。每个订单的客户

于 2013-09-19T13:10:55.250 回答