function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Salesforce@322Salesforce@322 

Fetching the previous week data of the object

Hi Salesforce Friends,

How to fetch the latest previous week data in salesforce?
My requirement is : Need to fetch records from a custom object which has been created past week.
If there is no record for past week, need to fetch the latest previous week.
If there is no record for that week also need to fetch the previous week of that week ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,etc
Kindly help me on how to fetch the latest previous week data.

Thanks ,,,,,,,,,,,,,
AshlekhAshlekh
Hi,

You can use where clause in soql where. By below code you can get the record which are created last 7 days
[select id from cusotmobject__c where CreatedDate>=: system.now()-7 ]
Previous to previous to week record can get by below get.
[select id from cusotmobject__c where CreatedDate>=: system.now()-14 and CreatedDate <=: system.now()-7]

Hope this code help you use this code according to your need in IF condations,

Please mark it as solution if helps you. Enjoying APEX
  
logontokartiklogontokartik
Hi Keerthi,

You can use Date functions like LAST_WEEK, LAST_MONTH, THIS_WEEK etc, but your requirement is to get data for latest previous week right? so you have to first identify which previous week has data and based on that you can query. This would require 2 queries altogether, 

One to get the latest previous week,

// Get the latest Previous week with the data
CustomObj__c obj = [Select Id, CreatedDate from CustomOBj__c where CreatedDate != THIS_WEEK order by CreatedDate desc LIMIT 1];

// Build Start and End of Weeks
Date startOfWeek = obj.CreatedDate.Date().toStartOfWeek();
Date endOfWeek  = startOfWeek.addDays(7); // Make sure if you want 7 days or 6 days. depending on req.

// Get the data
List< CustomObj__c> latestLastWeekRecs = [Select Id, CreatedDate from CustomObj__c where CreatedDate >= :startOfWeek AND CreatedDate <= :endOfWeek];


Hope this helps


SushumnaSushumna
Hi Guys,

This is quick. See below example:
 
SELECT o.ParentId, o.OldValue, o.NewValue, o.IsDeleted, o.Id, o.Field, o.CreatedDate, o.CreatedById FROM AccountHistory o
WHERE o.CreatedDate = LAST_N_DAYS:7

Also refer: https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_dateformats.htm

Hope this helps.