1

I have a trigger on after Insert and after update on Contact. This trigger updates Account.SalatySumLastContactsLast, with sum of Contact.Salary where Contact.mydate__c is latest. I simplified the logic for the question, I have to use trigger.

How can I wrote the query to select only contacts with contact.mydate__c is the latest.

SELECT id,(SELECT id FROM Contacts WHERE myDate ... ) from Account 
1

1 Answer 1

2

You can order by mydate__c to get the contact where mydate__c is latest.

SELECT Id,(SELECT Id FROM Contacts ORDER BY mydate__c DESC LIMIT 1) FROM Account 

updated Code:

map<String,Date> latestDateMap=new map<String,Date>();
for(Account acc : [SELECT Id,RollupSummary__c FROM Account /*WHERE Your filter*/]){
 latestDateMap.put(acc.Id,acc.RollupSummary__c );
}

List<Contact> conList=[SELECT Id FROM Contact WHERE AccountId IN :latestDateMap.keySet() AND mydate__c IN :latestDateMap.values()];
4
  • Thanks but I can have more than one contact with the same mydate__c which is latest
    – Raphael D
    May 26, 2021 at 8:25
  • What do you mean by latest here. Is is today's date, yesterday or N no of days? May 26, 2021 at 8:34
  • It is a custom date field, it can be yesterday , today , even tomorrow. In this case I want to take all Contacts where Contact.MyDate == tomorrow.
    – Raphael D
    May 26, 2021 at 9:06
  • What you can do is create a Roll-Up field on Account object to get the max/latest mydate__c for the number of Contacts added to it, then loop over Account to get the AccountId and latest date(rollup summary) and based on that fetch all the contact. I have updated code example in answer above. May 26, 2021 at 11:20

You must log in to answer this question.

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