R
R
road_warrior122022-04-03 13:33:30
MySQL
road_warrior12, 2022-04-03 13:33:30

How to count the number of regular customers?

Have a nice day, everyone. Faced such a task - to count the number of customers who had orders every day for the last month. There is an orders table, it has columns order_id, created (order creation date, datetime format) and user_id.
How to make it so that orders only for the last month are taken into account, I understand (my incomplete query will be below)
And how to make it so that only customers who placed an order every day are taken into account in the output?
Current code:
SELECT count(user_id)
FROM orders
WHERE DATE(created) >= DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH)

Thanks!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Slava Rozhnev, 2022-04-03
@rozhnev

SELECT user_id, count(distinct created)
FROM orders
WHERE created > DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY) -- get last 30 day orders
GROUP BY user_id
HAVING count(distinct created) = 30 -- check user have orders in 30 different days
;

MySQL sandbox

O
Oleg, 2022-04-03
@402d

Educational or real task?
In real life, I would simplify to
customers who have placed orders 30 days in the last 30 days.
we simplify the date time to the date
we count the number of unique days with orders for each client we
select those who have it equal to 30
And for educational purposes it is worth mastering the generation of a cursor with data (dates without a gap)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question