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

Best way to calculate difference between values on two different record?


I am having an requirement where in I have to calculate the difference between two values on different records of same object. For example lets say I have a number field on an object where its value is 150 on one record and the other record has value as 160 , so the difference here is 10(160-150 = 10). And most importantly I have calulate this based on the owner of the records.

Vamsi KrishnaVamsi Krishna
there can be more than 2 records owned by the same user.. so you will end up with a list of records and then you need to define your criteria on which 2 records you need to find out the difference...

List<YourObject__> objList = [Select Id,YourField__c from YourObject__c where OwnerId = 'YourUserId'];

this list can have minimum of 0, but also it can have more than 2 records...

you can apply filters based on your criteria to retrieve only 2 records ( here is simple one i m limiting it to max of 2)
List<YourObject__> objList = [Select Id,YourField__c from YourObject__c where OwnerId = 'YourUserId' limit 2];

then your difference will be
objList[0].YourField__c - objList[1].YourField__c;
Hi Vamsi,

Thats fine, i just need the latest two records for caluclating the difference; so sorting it by descending order of created date will give me those two.
So only one concern here I am having is that there are mor than 1000 users, So I would end up making an SOQL for each user.

And if consider using batch how would I make sure that only two latest records for each user is returned? One way to achive this is by keeping batch size to 1 and pass One user at a time.

Any ideas?

You can create trigger on that particular object to do the calculations. On update of that field just fetch the latest record of that owner [to get latest record use order by dsc], and do the calculations.

How would it be bulkified? will have to query for each of the record in