按计数分组?

时间:2013-09-19 13:04:14

标签: mysql sql

我有两张桌子:

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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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

here's an SQL Fiddle包含有效的查询和测试数据。

答案 3 :(得分:0)

您必须按订单分组才能获得否。每个订单上的客户