+ Start a Discussion
wendy chan 3wendy chan 3 

Help with Aggregate funtion

I have two object - Object A and Object B. Object A has a field "Total Amount" and Object B has a field "Amount". Both objects have NO relation with each other. What I want to do is bring in total SUM of "Amount" (from Object B) in "Total Amount" (of Object A) using trigger.

Below code only works if Total_Amount__c has some value in it. If I remove a value, I keep getting - [System.NullPointerException: Attempt to de-reference a null object: Trigger.RollupTrigger: line 14, column 1]

 
trigger RollupTrigger on Object_B__c (after insert,after update)
{
        Decimal decValue = 0;

   AggregateResult[] groupedResults = [SELECT  SUM(Amount__c)   FROM Object_B__c  GROUP BY ID];
    
for (AggregateResult ar : groupedResults)  {
    System.debug('Average amount' + ar.get('expr0'));

    
    For (Object_A__c A : [SELECT ID, Total_Amount__c from Object_A__c WHERE ID = 'a122800000154Mi'])
    {
         
        A.Total_Amount__c += (Decimal)ar.get('expr0');
        Update A;
        
       }
    }
}

 
NagendraNagendra (Salesforce Developers) 
Hi Wendy,

Amount is not a valid field for a custom object

Most likely is should be Amount__c

Per your updated comment this will solve the NPE
 
A.Total_Amount__c += (Decimal)ar.get('expr0') == null ? 0 : (Decimal)ar.get('expr0')

Hope this helps.

Please mark this as solved if it's resolved so that it gets removed from the unanswered queue which results in helping others who are encountering a similar issue.

Thanks,
Nagendra.