-1

I want to know the trick to find the list of customers who are transacting for consecutive 3 months ,that could be any 3 consecutive months with any number of occurrence.

example: suppose there is customer who transact in January then keep transacting till march then he stopped transacting.I want the list of these customer from my database .

I am working on AWS Athena.

  • Please provide sample data and expected results, as well as your current attempt at solving the problem. – GMB Nov 23 '19 at 21:11

1 Answers1

0

One method uses aggregation and window functions:

select customer_id, yyyymm_2
from (select date_trunc(month, transactdate) as yyyymm, customer_id,
             lag(date_trunc(month, transactdate), 2) over (partition by customer_id order by date_trunc(month, transactdate)) as prev_yyyymm_2
      from t
      where transactdate >= '2017-01-01' and
            transactadte < '2019-01-01'
     )
where prev_dt_2 = yyyymm - interval '2' month;

This aggregates transactions by month and looks at the transaction date two rows earlier. The outer filter checks that that date is exactly 2 months earlier.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786