2

I have a requirement where I need to fetch records from Previous 3 months to Today. When I tried using Last_n_Months :2 binding, I can only retrieve previous months records excluding current month.

Can anyone please help me with this Query.

Thank you in advance

2 Answers 2

3

Just add with or condition THIS_MONTH eg.

SELECT Id FROM Account WHERE CreatedDate = LAst_N_Months:2 or CreatedDate = THIS_MONTH
7
  • Thank you Rahul. But when I query using the above given soql, I am recieveing records from 2017, 12th month. I can only get correct records when I hardcode viz., Processing_MONTH__C IN (1,2,3,4,5,6,7,8,9,10,11,12). Please help
    – Sastri
    Commented Dec 26, 2018 at 10:28
  • @Sastri can paste the query you are using now? Commented Dec 26, 2018 at 10:32
  • @Sastri Are you sure, you used the same query? I tried it in my dev org and its working as expected. Commented Dec 26, 2018 at 10:44
  • 1
    My bad...I have tried this in my other org and it is working fine. Thank you Rahul for this effort. Cheers!
    – Sastri
    Commented Dec 26, 2018 at 10:46
  • @Sastri Welcome, Happy Coding!! Commented Dec 26, 2018 at 10:47
2

Try this:

Date today = System.today();
Date last_n_month = today.addMonths(-3);
List<sObject> list_sobj = [select id from sObject_API_Name where CreatedDate >=: last_n_month AND CreatedDate <=: today order by CreatedDate DESC];

Or:

List<Lead> list_sobj = [select id,CreatedDate from Lead where CreatedDate >= Last_N_Months:3 AND CreatedDate <= today order by CreatedDate DESC];
for(lead s:list_sobj){
    System.debug(s);
}
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .