Skip to content
Advertisement

Iterating through users and check if they exist in the past 12 months

DB-Fiddle

Expected Result:


I want to list all customers in a certain month which

a) exist in the past 12 months and
b) also exist in the current month.


For a single month I am able to achieve this by using this query:


However, I have to run this query for each month seperatly.

Therefore, I am wondering if there is an iterating solution that goes through multiple months at once.

In the example above it would run BETWEEN '2021-05-01 00:00:00' AND '2021-06-30 23:59:59' and calculate 12 months back from May and in the next step 12 months back from June to get the expected result.

Do you have any idea if this is possible?

Advertisement

Answer

Use LAG() to check if there is an order in the previous 12 months:

Here is a db<>fiddle.

Note that I fixed the date comparisons so you are not fiddling with seconds when defining a month timeframe.

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