1

I am looking at the Salesforce Documentation for working with SOQL Aggregate Functions and seeing that we need to leverage .get to access the specific column value. Is there a built in method for attaining all the column values? I ask because this would add a layer of abstraction to the code.

Below is documentation that Salesforce currently provides:

AggregateResult[] groupedResults = [SELECT CampaignId, AVG(Amount)FROM Opportunity GROUP BY CampaignId];
for (AggregateResult ar : groupedResults)  {
    System.debug('Campaign ID' + ar.get('CampaignId'));
    System.debug('Average amount' + ar.get('expr0'));
}

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL_agg_fns.htm?search_text=aggregateresult

1 Answer 1

5

Your question isn't entirely clear (are you looking for field names, or the values of all fields?) In the end though, it doesn't matter which. Turns out you can still use getPopulatedFieldsAsMap() (API v39.0, aka Summer '16), which gives you both.

  • You'd be able to see all of the field names queried (look at the keyset)
  • You'd be able to see all of the field values (look at the values)
for(AggregateResult ar :[SELECT Name, Count(Id) FROM Account GROUP BY Name]){
    Map<String, Object> popFields = ar.getPopulatedFieldsAsMap();
    system.debug(popFields.keySet()); // gives you "Name" and "expr0"
    system.debug(popFields.values()); // gives you something like "Test Account" and "2"
}

As the type of the map shows, however, you get Object typed values out of this (same as if you'd use .get() on an AggregateResult ...or any SObject, for that matter). It's going to be difficult (or at least take more work) to be able to figure out what the type of the field values should be.

You must log in to answer this question.

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