Skip to content
Advertisement

HOW TO CHECK CONDITIONS FOR PREVIOUS MONTH

My table is like

RUNDATE    TRANSACTION_ID   CUSTOMER_ID   TRANSACTION_TYPE
18/10/2020  2464            4007715       T9

I am trying to get customer_ids where they didn’t do any transactions previous month and made transactions with at least 2 transaction_type at this_month.While doing this I am converting rundate to MM-YYYY format. What I’ve done for getting previous month and this month on MM-YYY format is :

SELECT EXTRACT( MONTH FROM RUNDATE )|| '-' || EXTRACT(YEAR FROM RUNDATE ) AS MONTH_YEAR,
TRANSACTION_TYPE,
CUSTOMER_ID,
TRANSACTION_ID,
EXTRACT( MONTH FROM PREV_MONTH)|| '-' || EXTRACT(YEAR FROM PREV_MONTH) AS PREV_MONTH_YEAR FROM
(
SELECT TRANSACTION_ID,RUNDATE,CUSTOMER_ID,TRANSACTION_TYPE, ADD_MONTHS(rundate ,-1) as PREV_MONTH
FROM TRANSACTIONS
)

and this is what i got:

PREV_MONTH_YEAR MONTH_YEAR  TRANSACTION_TYPE   CUSTOMER_ID
9-2020          10-2020      T9                4007715


But the problem is I couldn’t figure how to check my conditions for both PREV_MONT_YEAR AND MONTH_YEAR at the same time

Advertisement

Answer

You can use window functions: You can aggregate by month and use window functions:

SELECT t.*
FROM (SELECT t.CUSTOMER_ID, TRUNC(RUNDATE, 'MON') as RUN_MONTH,                 
             COUNT(*) as cnt_this_month,
             LAG(TRUNC(RUNDATE, 'MON')) OVER (PARTITION BY CUSTOMER_ID) as PREV_RUNMONTH
       FROM TRANSACTIONS t
       GROUP BY CUSTOMER_ID, TRUNC(RUNDATE, 'MON')
      ) t
WHERE cnt_this_month >= 2 and 
      (prev_runmonth is null or prev_runmonth < run_month - interval '1' month);

Note: This truncates the date to the first day of the month. I prefer working with dates rather than strings. Of course, you can use to_char(runmonth, 'YYYY-MM') if you prefer strings.

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