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
Dave ShulmanDave Shulman 

Looping through AggregatedResults

Im trying to loop through an AggregatedResult.   
AggregateResult[] groupedResults = [SELECT End_user__c,Distributor__c,SUM(Amount__c) 
                                               FROM Sales_data__c 
                                               WHERE Date__c >= :AfterDate 
                                                    AND Sales_Type__c = 'Actual' 
                                         			AND End_user__r.ID IN :accountIds
                                               GROUP BY End_user__c, Distributor__c
                                               ORDER BY End_user__c, SUM(Amount__c)];
how do i loop through this to get the first Distributor ID for each End User.  We're trying to capture the primary distributor for each End User based on Amount.  Please let me know how to loop through this and get the information  
 
Best Answer chosen by Dave Shulman
David Zhu 🔥David Zhu 🔥
You may refer to the code snippet below. endUserMap contains end user and distributor mapping information.
AggregateResult[] groupedResults = [SELECT End_user__c,Distributor__c,SUM(Amount__c) 
                                               FROM Sales_data__c 
                                               WHERE Date__c >= :AfterDate 
                                                    AND Sales_Type__c = 'Actual' 
                                         			AND End_user__r.ID IN :accountIds
                                               GROUP BY End_user__c, Distributor__c
                                               ORDER BY End_user__c, SUM(Amount__c)];

Map<String,String> endUserMap = new Map<String,String>();

for (AggregateResult ar : groupedResults)  {
	String endUser = String.valueOf(ar.get('End_User__c'));
	String distributor= String.valueOf(ar.get('Distributor__c'));

        if (!endUserMap.containsKey(endUser)){
		endUserMap.put(endUser,distributor);
        }
}