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.
There are several ways of doing this.
One would be to sort your GroupBy results using a for loop.
Another would be to put the results into map(s). Then take the top two results from your sorting in order to get them for the respective parents.
Since you're using a GroupBy, you could also presumably return something "like" ar[0].cnt, ar[0].Parent__r.Primary_Category__c
and ar[1].cnt, ar[1].Parent__r.Primary_Category__c
to get the top two for the parent with the "most" results and compare the two Parent_r's
to see if they're the same. If they're not, you have the two that you're looking for that are at the top.
If they are the same, you'll need to test ar[3]
, ar[4]
, etc until you find a different Parent__r
to assign as the second parent.
From the above, you'll already know the results for the highest Primary_Category__c
for the first Parent__r
and for the 2nd one as well. Now you need to sort the secondary category based on the what you learned determined to be the 1st and second parents.
I believe this is where you may want to put the results into two maps.
Beginning with the 1st parent, do a for loop to add the results of a loop to the map if the parent and the secondary_category__c
matches parent__r
that was the 1st parent
and secondary_category__c isEmpty() == false
. The first result you find will be the one you're looking for. Rather than putting it into a map, you could break
from the for loop
if you wanted to. the choice would be yours to make.
You'd repeat the same process above for the other parent__r
.
Best Answer
Suggested solution:
Convert a list of aggregate results to a Json string and deserialize the string as an object.