2

I am trying to create a map of Opportunity ids and a count of its Opportunity Line Items.

Map<Id,Integer> opptyIdLineCount = new Map<Id, Integer>();
AggregateResult[] aggOpptyIdLineCount = [SELECT OpportunityId, COUNT(Id)count
                                         FROM OpportunityLineItem
                                         GROUP BY OpportunityId];
for(AggregateResult agg : aggOpptyIdLineCount){
    opptyIdLineCount.put((Id)agg.get('Id'), Integer(agg.get('count')));
}

Shows error-

Unexpected token '['

when I try to run this snippet in Anonymous Window. I've tried the using List<AggregateResult> as well but shows

Unexpected token '<'

What am I missing?

4

count is a reserved word and cannot be your alias. Change it to somenthing like recordCount and your query will work

Example:

AggregateResult[] aggOpptyIdLineCount = [SELECT OpportunityId, COUNT(Id) recordCount
                                         FROM OpportunityLineItem
                                         GROUP BY OpportunityId];
2
  • You'll also need the right key for the OpportunityId. Either add an alias (that's not a reserved word like 'Id') or use the full field name in your agg.get() Jul 2 '19 at 19:26
  • Thank you Sebastian and Thomas. The snippet worked after I made the changes: AggregateResult[] aggOpptyIdLineCount = [SELECT OpportunityId, COUNT(Id)recordCount FROM OpportunityLineItem GROUP BY OpportunityId]; for(AggregateResult agg : aggOpptyIdLineCount){ opptyIdLineCount.put((Id)agg.get('OpportunityId'), (Integer) (agg.get('recordCount'))); }
    – Rithu
    Jul 2 '19 at 19:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.