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
Nandhini GovindrajNandhini Govindraj 

Sum all revenue of child accounts tp parent in account hierarchy

Hi

I have created a field Total Annual Revenue .
Result should be lik
Parent Ann revenue-5 total ann rev-12
Child Ann rev-2 total Ann Rev-7
Grant Child Ann rev-5 total Ann Rev-0

For this i used this code
trigger TotalAnnualRevenueChildAccount on Account (after insert,after update) {
    Set<Id> accids=new Set<Id>();
      if(trigger.isinsert || trigger.isupdate && trigger.isafter){
         for(Account acc:trigger.new){
            accids.add(acc.Id);
         }
      Map<Id,Account> maccid=new  Map<Id,Account>();
      for(AggregateResult ar:[select Id,sum(AnnualRevenue)TotalAnnRev from Account where ParentId=:accids Group by Id]){
         Account ac=new Account();
         ac.Id=(Id)ar.get('Id');
         ac.Total_AnnualRevenue__c=(Double)ar.get('TotalAnnRev');
         maccid.put(ac.Id,ac);
         }
       update maccid.values();  
        } 
      }

I am not getting the result as i mention above..
AnkaiahAnkaiah (Salesforce Developers) 
Hi Nandhini,

try with below code.
trigger TotalAnnualRevenueChildAccount on Account (after insert,after update,after delete) { 
    Set<Id> accids=new Set<Id>();
if(trigger.isinsert || trigger.isupdate && trigger.isafter){
for(Account acc:trigger.new){ 
    if(acc.ParentId!=null){
     accids.add(acc.ParentId);        
    }

}
if(Trigger.isDelete){

for(Account acc_Old : Trigger.old){

if(acc_Old.ParentId!=null)

accids.add(acc_Old.ParentId);

}

}
    List<Account> Listaccount= new List<Account>(); 
    Map<Id,Double> mapChildTotalAmount = new Map<Id,Double>();
 for(AggregateResult ar:[select parentId,sum(AnnualRevenue) from Account where ParentId IN: accids Group by parentId]){

     mapChildTotalAmount.put((Id)ar.get('ParentId'),(Double)ar.get('expr0'));
 }
    for(account acc:[select id,Total_AnnualRevenue__c from account where id=:mapChildTotalAmount.keyset()]){
        if(mapChildTotalAmount.containskey(acc.id)){
            acc.Total_AnnualRevenue__c=mapChildTotalAmount.get(acc.id);
            Listaccount.add(acc);
        }
    }
if(Listaccount.size() > 0){
update Listaccount; 
} 
} 
}

If this helps, Please mark it as best answer.

Thanks!!​​​​​​​