function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Mounika VarmaMounika Varma 

My Requirement is I had Created a TotalAmount field on Account Object, I need to sum of the opportunity amount for all the opportunities for that account. using Batch class

This is my code and i am not getting results 

global class batchclass implements Database.Batchable<sObject>,Database.Stateful{
    global Decimal sum;
     /* Batch class constructor */
    global batchclass(){}
    //Start method
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        String query='SELECT id, Amount from Opportunity';
         return Database.getQueryLocator(query);
        }

    //Excute method
    
global void execute(Database.BatchableContext BC, List<Opportunity> scope)
{
    //Excution logic
    //List<Opportunity> opp= new List<Opportunities>();
    AggregateResult[] gr=[select id,TotalAmount__c,(select amount from Opportunities) from account where id IN:accountIds];
        system.debug(gr);
    for(AggregateResult ag:gr){
        sum = (Decimal)ag.get('optyamt');
        system.debug(''+sum);
    }
    
}
      global void finish(Database.BatchableContext BC){
            // Finish logic
          system.debug(''+sum); 
       }
}
AbhinavAbhinav (Salesforce Developers) 
Hi Mounika,

You are using IN:accountIds how you are getting this list of accountIds?

Thanks!
Suraj Tripathi 47Suraj Tripathi 47
Hi mounika,

You can take reference from this below code:-
global class batchclass implements Database.Batchable<sObject>,Database.Stateful{
    
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        String query='select id,TotalAmount__c from account ';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<Account> scope)
    {
        
        List<opportunity> oppList=[select id, amount,accountid from Opportunity where accountid IN:scope and amount!=null];
        map<id,decimal> accidVsCountAmount = new map<id,decimal>();
        for(opportunity opp:oppList){
            if(!accidVsCountAmount.containskey(opp.accountid)){
                accidVsCountAmount.put(opp.accountid,opp.amount);
            }
            else{
                decimal count=accidVsCountAmount.get(opp.accountid);
                count=count+opp.amount;
                accidVsCountAmount.put(opp.accountid,count);
            }
        }
        for(account acc: scope){
            if(accidVsCountAmount.containskey(acc.id)){
                acc.TotalAmount__c = accidVsCountAmount.get(acc.id);
            }
        }
        update scope;
    }
    global void finish(Database.BatchableContext BC){
        system.debug('finish'); 
    }
}

In case you find any other issue please mention. 
If you find your Solution then mark this as the best answer. 

 
CharuDuttCharuDutt
Hii Mounika
Try Below Code With Test Class
global class batchclass implements Database.Batchable<sObject>,Database.Stateful{
    
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        String query='select id,Total_Amount__c from Account ';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<Account> scope)
    {
        integer i = 0;
        List<Opportunity> lstOpp=[select id,Amount,AccountId from Opportunity where AccountId IN:scope];
       
        for(Opportunity Opp:lstOpp){
            i=i+integer.valueof(Opp.salary__c);
    
        }
        for(Account acc: scope){
           
                acc.Total_Amount__c = integer.valueof(i;
            
        }
        update scope;
    }
    global void finish(Database.BatchableContext BC){
        Id job = bc.getJobId();
    }
}

-------------------------------------------------------------------

Test Class
@isTest
public class BatchClassTest {
  @isTest
  static void setup() {
      account acc = new account() ;
      acc.Name = 'test' ;
      
      insert acc;
        List<Opportunity > lstOpp= new List<Opportunity >();
    for(Integer i=0; i <100; i++) {
        Opportunity Opp = new Opportunity ();
           Opp.Name = 'Test Opp'+i;
            Opp.AccountId = acc.id;
            Opp.Amount= 100+i;
            Opp.StageName = 'Closed Won';
            Opp.CloseDate = System.Today();
            lstOpp.add(Opp );
    }
        insert lstOpp;
    

    

    batchclass lp =new batchclass();
    Id batchId = Database.executeBatch(lp);
    }
}



Please Mark It As Best Answer If It Helps
Thank You!
Al Awan PropertiesAl Awan Properties

If you have cash in your hand, Real Estate Pakistan is a large platform where you can invest. It's a long-term investment, so you'll need to have some home furnishings on hand. Al Awan Properties (https://alawanproperties.com.pk) in Islamabad may assist you in making real estate investments in Pakistan, (https://alawanproperties.com.pk/blue-world-city/) particularly in Islamabad. Al Awan Properties will also contribute to the development of Bahria Town, which is set to open soon. Please visit (https://alawanproperties.com.pk)  (https://alawanproperties.com.pk/societies/nova-city-islamabad/) for more information.