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
Sangeeth R 5Sangeeth R 5 

Is there any Problem in the Query i used?

The Object 'Product__c'  is in master detail relation with the object 'Order_Product__c' .the object 'Order_Product__c' consists of a custom field 'Quantity' ,the average should be calculated for the 'Quantity' fields of all the records, that average should be updated in another Object 'Product_maintanance__c's' field which is the parent of Object 'Order_Product__c'.  the average should be updated separately based on the Object 'Product__c' ID .The Object 'Product__c' is the Parent of Object 'Product_maintanance__c'.


When I try this method, The field get's updated in Object 'Product_maintanance__c' but not based on the Object 'Product__C' Id. it updates the same Quantity value to all the fields in Object 'Product_maintanance__c'.

 global class BatchapextoUpdateQuantity implements Database.Batchable<SObject>,Schedulable {
        
        global Decimal avg;
        
        global Database.querylocator start(Database.Batchablecontext bc){
           string  query='select id from Product_maintanance__c';
            return database.getQueryLocator(query);
        }
        global void execute(Database.BatchableContext BC, list<sObject>prolst){
            
           productMaintananceHelper pmh=new ProductMaintananceHelper();
           pmh.Quantity();
           
      AggregateResult[] result= [select ProductESB__c,avg(Quantity__c)aver from Order_Product__c  group by productESB__c];
              for( AggregateResult ar : result){
              avg=(Decimal)ar.get('aver');
              }
            list<Product_maintanance__c> pmlst=new list<Product_maintanance__c>();
                list<Product_maintanance__c> prodlist=[select id from Product_maintanance__c];
            for(Product_maintanance__c pm : prodlist){
                pm.Quantity_del__c=avg;
                 pmlst.add(pm);
            }
                    if(pmlst.size()>0){
                try{
                    update pmlst;
                }
                catch(Exception e){
                    System.debug('Exception is '+e.getMessage());
                }
                    }
        }
        
        
        global void finish(Database.Batchablecontext bc){
            
        }
        global void execute(SchedulableContext sc) {
            BatchapextoUpdateQuantity ba=new BatchapextoUpdateQuantity();
            Database.executeBatch(ba);
             //string sch = '0 00 00 * * ?';
         //system.schedule ('Batch', sch, new BatchapextoUpdateQuantity());
        }
        
    }