Filtering previous month data with case statement

casedateoracle

These are my available attributes:

DT_CURRENT_DT Month Year
11-OCT-18     10    2018
12-OCT-18     10    2018
13-OCT-18     10    2018
14-OCT-18     10    2018
15-OCT-18     10    2018
16-OCT-18     10    2018
17-OCT-18     10    2018

I need a logic that will pull last month data based on sysdate.

where DT_CURRENT_DT >=  trunc (sysdate, 'MM') - interval '1' month
and DT_CURRENT_DT <   trunc (sysdate, 'MM')

However when sysdate = November 2018 then data must be pulled from October 15th till end of October. For other months it must behave as code above.

UPDATE (NOV 11) – CASE code version:

WHERE  DT_CURRENT_DT >= CASE 
                       WHEN extract ( month from trunc (sysdate, 'MM')) = 11 and extract ( year from trunc (sysdate, 'MM')) = 2018
                       THEN to_date('15-OCT-2018')
                       ELSE  trunc(sysdate, 'MM') - interval '1' month
                       END
AND DT_CURRENT_DT <   trunc (sysdate, 'MM') 

Best Answer

Try to change the where clause to the following:

where DT_CURRENT_DT >= trunc (sysdate, 'MM') - interval '1' month
  and DT_CURRENT_DT < trunc (sysdate, 'MM')
  and (
       trunc(sysdate, 'MM') != to_date('01-NOV-2018')
       or extract(day from DT_CURRENT_DT) >= 15
      );