Skip to content
Advertisement

How to find whether the same customers who ordered this month also ordered the next month?

I have an orders table

Now I want to find how many of the users ordered in 1st month also ordered in the next month. In this case, user_id’s 32,24,27 ordered in 7th month but only 24 and 32 ordered in the next month.

I want the result to be like :

I’m lost here. Can someone please help me with this?

Advertisement

Answer

In MySQL 8.0, you can do this with window functions:

The logic lies in the range specification of the window function; it orders record by month, and counts how many orders the customer placed last month. Then all that is left to do is aggregate and count distinct users.

Demo on DB Fiddle

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