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
David Baumann 31David Baumann 31 

How to access field value in AggregateResult list

I use the follwing query to find the median account revenue
List<AggregateResult> totalOppsClosedWon365 = [select AccountId, sum(Amount__c) Revenue, Account.Stage__c
 from Opportunity
where CloseDate = LAST_N_DAYS:365 and StageName = 'Closed Won' 
group by AccountId, Account.Stage__c
order by sum(Amount__c) asc];
but how do I access the Revenue value at the specific index which marks the center of the list? For example the Revenue at index 100 because this is the center of the list. 

I apprechiate any help! 
 
Deepali KulshresthaDeepali Kulshrestha
Hi David,
Greetings to you!

You can do this in two ways:
1st is by iterating totalOppsClosedWon365  using the loop

   for(AggregateResult Obj : totalOppsClosedWon365 ){
    System.debug('Revenue :' + Obj .get('Revenue') );
}

2nd by using the index because 
Note that any query that includes an aggregate function returns its results in an array of AggregateResult objects. AggregateResult is a read-only sObject and is only used for query results. 

System.debug('Revenue :' + totalOppsClosedWon365 [0].get('Revenue') );

For more details visit this link: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL_agg_fns.htm

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha.