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
MohiniMohini 

Trigger to perform average or sum of child records on parent object based on product type

Hi there.. I need help with a trigger which averages sub opportunities revenue field  when product type is same else it sums the revenues  at the parent (opprtunity object).
The trigger  which I have written below only sums. Please help me so that based on the similar product types the revenue gets averages else sumed up.

trigger RolllupSubAmt  on Sub_Opportunity__c ( after insert, after update,after delete,after undelete) {
     Set<Id> oppIdSet=new Set<Id>();
     List<Opportunity> opptyListToUpdate=new List<Opportunity>();
     if(Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete){
          for(Sub_Opportunity__c subopp : Trigger.new){
             if(subopp.Opportunity__c!= null){
                oppIdSet.add(subopp.Opportunity__c);
             }      
          }
     }
     If(Trigger.isDelete){
       for(Sub_Opportunity__c opp : Trigger.old){
            if(opp.Opportunity__c!= null){
               oppIdSet.add(opp.Opportunity__c); 
            }       
        }
      }
     for(AggregateResult res : [SELECT Opportunity__c,sum(Actual_Revenue_Rollup__c)can FROM Sub_Opportunity__c WHERE Opportunity__c IN :oppIdSet GROUP BY  Opportunity__c ]) {
        opptyListToUpdate.add(new Opportunity(Id=(Id)res.get('Opportunity__c'), Actual_Revenue2__c=(Double)res.get('can')));
    }
    try{
        update opptyListToUpdate;
     }catch(DmlException de){
        System.debug(de);
     }
}
AnkaiahAnkaiah (Salesforce Developers) 
Hi Meera,

What is the issue, you were facing?

Thanks!!
MohiniMohini
Hi Ankaiah,

Thanks for responding. I need help with getting average of child sub opportunity revenue field at opportunity if product type is same. In case where producttype of sub opportunity is different , the revenue field will be sum.  For example ( if there are 2 rsub records with product type is "A" , revenue will be averaged for those two records and displayed at primary .else for different product type records revenue be added
MohiniMohini
Ankaiah will you be able to help me with the code