Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group by count possible?

Tags:

sql

mysql

i have 2 tables:

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

I want to know this:

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

i have this:

SELECT COUNT(co.id)
FROM customer c
LEFT JOIN customer_order co
ON c.id=co.id_customer
GROUP BY ??? ;
like image 858
orki2 Avatar asked Nov 27 '25 06:11

orki2


1 Answers

This gives the amount of orders per customer

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

Now use that as a table, and query it

SELECT Orders, COUNT(*)
FROM (
  SELECT co.id Customer, COUNT(*) Orders
  FROM customer_order co  
  GROUP BY co.id_customer;
)
GROUP BY Orders
like image 128
Konerak Avatar answered Nov 28 '25 21:11

Konerak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!