Skip to content
Advertisement

Get users that made order every month from MySQL

This is my database table: orders

id user_id order_id datetime
1 1 1245652 1607444387
2 2 3265784 1607357987
3 1 9521014 1607357927
4 3 1036951 1607317987

I want to have a list of users that place at least one order every month. how i can do that?

Advertisement

Answer

You can do something like this:

select user_id
from orders o
where datetime >= :from and datetime < :to
group by user_id
having count(distinct extract(year_month from from_unixtime(datetime))) = :num_months

:from, :to, and :num_months indicate parameters. The first two define the date range you want. The third indicates the number of months that constitute “every month” in the time frame.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement