+ Start a Discussion
Ram chowdaryRam chowdary 

Batch apex to Total amount sum in opportunities

Hi Folks, I have a use case that I need to display total  amount sum from opportunities object in finsh method... please help me ...
Go through these two articles. You will be able to form the query by yourself.

Please mark the answer as resolved if it resolved your question
Here is the implementation. You have to implement these three classes to achieve the desire result. I created a table to store the Opportunity Sum.
global class AggregateResultIterator implements Iterator<AggregateResult> {
   AggregateResult [] results {get;set;}
   // tracks which result item is returned
   Integer index {get; set;} 
   global AggregateResultIterator() {
      index = 0;
	  // Fire query here to load the results
      String query = 'SELECT SUM(Amount)OpptySum FROM Opportunity';
      results = Database.query(query);            
   global boolean hasNext(){ 
      return results != null && !results.isEmpty() && index < results.size(); 
   global AggregateResult next(){        
      return results[index++];            
global class AggregateResultIterable implements Iterable<AggregateResult> {
   global Iterator<AggregateResult> Iterator(){
      return new AggregateResultIterator();
global class IterableAggregator implements Database.Batchable<AggregateResult> {
    integer counter = 0;
    integer opptsumx = 0;
    list<testopptysum__c> oplst = new list<testopptysum__c>();
    testopptysum__c op; 
    global Iterable<AggregateResult> start(Database.batchableContext info){
        // just instantiate the new iterable here and return
        return new AggregateResultIterable();

    global void execute(Database.BatchableContext BC, List<AggregateResult> scope){
        for (AggregateResult so : scope)  {
          AggregateResult ar = (AggregateResult) so;
          counter = Integer.valueOf(ar.get('OpptySum'));
            opptsumx = opptsumx + counter;
          // process the results
		op = new testopptysum__c();
        op.opptsum__c = opptsumx;
        insert op;        

    global void finish(Database.BatchableContext BC){

Please mark thisanswer as the best answer if it resolved your issue
Hello, Your issue got resolved? 
Mari DanaMari Dana
Hi Prolay,

Do you know how to add test code for this. I am trying to add the test code but it is covering only the start method.It is not covering the execute method.
Can you please help me for this?