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
Pradeep Pradhan 21Pradeep Pradhan 21 

Create a TotalAmount field on account object, and need to sum of the opportunity amount for all the opportunity which is closed won for that account, use batch class.

Hi All
please help me to write batch class
Sai PraveenSai Praveen (Salesforce Developers) 
Hi Pradeep,

Can you check the below logic for the same.
 
global class batchclass1 implements Database.Batchable<sObject>,Database.Stateful{
    global Decimal sum;
    global batchclass1(){}

    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        String query='SELECT id, Amount from Opportunity';
         return Database.getQueryLocator(query);
        }


    
global void execute(Database.BatchableContext BC, List<Opportunity> scope)
{

    AggregateResult[] ar= [SELECT SUM(Amount) optyamt FROM Opportunity];
    
    for(AggregateResult ag:ar){
        sum = (Decimal)ag.get('optyamt');
    }
    
}
      global void finish(Database.BatchableContext BC){
            // Finish logic
          system.debug(''+sum); 
       }
}

Reference: https://developer.salesforce.com/forums/?id=906F0000000MImGIAW


If this solution helps, Please mark it as best answer. If you face any issues let me know so i can help you.

Thanks,
 
CharuDuttCharuDutt
Hii Pradeep
Try Below Code
public class AccountProcessor implements Database.Batchable<sObject> {
    public Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator('SELECT Id,Name,Amount,AccountId FROM Opportunity where Stage = "Closed Won"');
    }
    public void execute(Database.BatchableContext bc, List<Opportunity> records){
         Map<String,decimal> AccountMap = new Map<String, decimal>();
        
        for(Opportunity Opp : records){
            decimal val = 0;
          val += Opp.Amount;
            AccountMap.put(Opp.AccountId, Opp.Amount);
        }
        list<Account> lstAcc = [Select Id,TotalAmount__c from Account Where Id in :AccountMap.keySet()];
        for(Account Acc : lstAcc){
            if(AccountMap.containsKey(Acc.id)){
                Acc.TotalAmount__c = AccountMap.get(Acc.id);
            }
        }
        update lstAcc;
    }
    public void finish(Database.BatchableContext bc){
        Id job = bc.getJobId();
    }
}
Please Mark It As Best Asnwer If It Helps
Thank You!