I have the following code;

List<Account> accs = [SELECT Id, TotalVisitbyCurrentOwner__c, OwnerSince__c, Owner.Id FROM Account WHERE AccountCountry__c = 'ID' AND (TypeOfCompany__c = 'Developer' OR TypeOfCompany__c = 'Bank') AND Owner.IsActive = true ];
        system.debug('total account = ' + accs);

        Map<Id, Account> accIds = new Map<Id, Account>();

Map<Id, AggregateResult> meetingActivities = new Map<Id, AggregateResult>([SELECT MAX(CompletedDate__c) datemax, WhatId Id FROM Task WHERE (Type__c = 'Meeting' OR Type__c = 'meeting')  AND Status = 'Completed' AND CallResult__c = 'Successful' AND  WhatId IN: accIds.keySet() GROUP BY WhatId]);

        system.debug('total of meeting activities = ' + meetingActivities);

for(Account temp : accs){

                temp.TotalVisitbyCurrentOwner__c += 1;
                temp.DateofLastVisit__c = Date.valueof(meetingActivities.get(temp.Id);
        update accs;

inside for loop, I need to populate field DateofLastVisit__c from the aggregate result "datemax" that corresponds to the id of the Account in the loop. how do I do this?

1 Answer 1


Just use get method as you would on SObject.

AggregateResult aggregateRecord = aggregates.get(...);
Date aggregateValue = (Date)aggregateRecord.get('dateMax');

If you hadn't given the field an alias, it would instead be .get('expr0').

  • Sorry but I still dont follow, the aggregate result is in the map object, if I put meetingActivities.get(temp.Id) then I get AggregateResult:{datemax=Wed Dec 11 00:00:00 GMT 2019, Id=0016E000014kNP7QAM} , I need to access only the datemax Jul 16, 2020 at 12:50
  • Yes exactly...so you call .get('dateMax') on that AggregateResult. meetingActivities.get(temp.Id).get('dateMax')
    – Adrian Larson
    Jul 16, 2020 at 13:04

You must log in to answer this question.

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