i have table like this (each row represents an order):
order_id date customer_id
11 '2023-01-01 00:03:43' 123
12 '2023-02-01 00:02:43' 456
13 '2023-02-01 00:03:44' 789
14 '2023-04-01 00:03:43' 1230
i tried this:
SELECT DATE_FORMAT(date,'%Y-%m') , COUNT(distinct customer_id) as count
FROM `order` o
GROUP BY DATE_FORMAT(o.date,'%Y-%m')
HAVING COUNT(o.customer_id) > 1
It works but also counts customers from previous months. For example, a customer counted in January should not be counted in February. How can I do that ?
3
Answers
try this query. Return the result of all distinct customer counts per month and year-wise.
To ensure that each customer is counted just once, we will obtain the earliest date possible for each customer using
groub by
andmin()
:Then apply your logic using
group by
andhaving
on this dataset :Demo here
You can first find out which customers have more exactly two orders per month:
Now that you have that list, you can calculate number of customers per month:
See db-fiddle