+ Start a Discussion
Laurie DrewLaurie Drew 

Error trying to build a map

Hi, 

I am trying to build a map that will contain the Account OwnerId as the key and the sum value of the field Amount grouped by Month and Year as the value and receiving the error:

"Loop variable must be a generic SObject or LIst or a concrete SObject or List of: AggregateResult"

Here is my code, can anyone help me fix what I am doing wrong?


Map<Id,Decimal> invoices = new Map<Id,Decimal>();
for(Invoice__c obj:[Select Account__r.OwnerId, sum(Amount__c) FROM Invoice__c group by Account__r.OwnerId, Calendar_Year(InvoiceDate__c), Calendar_Month(InvoiceDate__c)]){
    invoices.put(obj.Account__r.OwnerId,obj.Amount__c);
}
Best Answer chosen by Laurie Drew
Karthikeyan Rajendran 14Karthikeyan Rajendran 14
Hi Laurie 

     Since you have Aggregate function "Sum" in your query you have to use AggregateResult. Here is the code to fetch the values.
Map<Id, Decimal> invoices = new Map<Id,Decimal>();

for(AggregateResult result : [Select Account__r.OwnerId accOwner, sum(Amount__c) amt from
                                              Invoice__c group by Account__r.OwnerId, 
                                              Calendar_year(InvoiceDate__c), 
                                              Calendar_Month(InvoiceDate__c)]){

          invoices.put((Id) result.get('accOwner'), (Decimal) result.get('amt'));
}

   Regards
   Karthik

All Answers

Andrew GAndrew G
Hi Laurie

I would investigate how to use the AggregateResult feature of Salesforce/Apex.

Basically, you query is returning an AggregateResult list not a list of Invoice Objects.

Regards
Andrew
Karthikeyan Rajendran 14Karthikeyan Rajendran 14
Hi Laurie 

     Since you have Aggregate function "Sum" in your query you have to use AggregateResult. Here is the code to fetch the values.
Map<Id, Decimal> invoices = new Map<Id,Decimal>();

for(AggregateResult result : [Select Account__r.OwnerId accOwner, sum(Amount__c) amt from
                                              Invoice__c group by Account__r.OwnerId, 
                                              Calendar_year(InvoiceDate__c), 
                                              Calendar_Month(InvoiceDate__c)]){

          invoices.put((Id) result.get('accOwner'), (Decimal) result.get('amt'));
}

   Regards
   Karthik
This was selected as the best answer