Can I assign Aggregate SOQL Result directly to variable?

Salesforce documentation suggests that aggregrate soql results must first be assigned to an instance of the AggregateResult class, as shown below:

    AggregateResult[] groupedResults = [SELECT AVG(Amount)aver FROM Opportunity]; 
    Object avgAmount = groupedResults[0].get('aver');

I’m wondering, is it possible for a more elegant solution that assigns the aggregated field directly to a variable of the same type? EG:

mainAccount.Active_Total_Opps_Rollup__c = [SELECT SUM(Amount) FROM Opportunity WHERE AccountID IN :ID_Group];

Obviously what I’ve written gives an error, because the query returns a list of results and not a single value. But is there a way for me to compactly indicate that I want to return only the aggregated value?

Answer

You cannot simplify the query, but you can the assignment…

Decimal avgAmount = (Decimal) [SELECT AVG(Amount)aver FROM Opportunity][0].get('aver');

Normally I would have said this was a little unsafe, since your always assuming you have one item in the result array the aggregate query returns. However I’ve just tested it and even if the object has no records in it you do get an a single aggregate result. However the value of ‘aver’ is null.

Attribution
Source : Link , Question Author : smohyee , Answer Author : Andrew Fawcett

Leave a Comment