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
Kiran Hunnaragi 25Kiran Hunnaragi 25 

summing of child account on parent account

Hi All,

We have a requirement to calculate all child accounts amount field and show it on the parent account.

We have look up relationship so we need to write a trigger for this. Can I someone help on this requirement??

I have got a sample code in google however it is not working please check

Amount field 
__________________________________________________________
trigger ParentAccUpdate on Account  (after insert,after update, after delete,after undelete) {
    if(checkRecursive.runOnce())
        
    {
        
        
        List<id> ParentIds = new List<id>();
        if(Trigger.isInsert || Trigger.isUndelete || Trigger.isupdate){
            For(Account Acc: Trigger.new){
                ParentIds.add(Acc.parentid);
            }
        }
        if(Trigger.isDelete){
            For(Account Acc: Trigger.old){
                ParentIds.add(Acc.parentid);
            }
        }
        List<account> accountToUpdate = new List<account>();
        decimal sum = 0;
        
        if(Trigger.isInsert || Trigger.isUndelete || Trigger.isupdate || trigger.isdelete){
            For(account q : [SELECT Total_Revenue_2021__c ,X2020_Revenue__c, (SELECT id,X2020_Revenue__c,Total_Revenue_2021__c FROM  ChildAccounts) FROM account WHERE id =: ParentIds]){ 
                sum = 0;
                
                for(Account p : q.ChildAccounts){
                    
                    sum = sum + (q.X2020_Revenue__c!=NULL ? q.X2020_Revenue__c : 0);//Use the fields you want here to get the sum and include those                     fields in above query eg is given below from my understanding
                                   

                    q.Total_Revenue_2021__c = sum;
                    
                    
                }
                accountToUpdate.add(q);
            }
            try{
                update accountToUpdate ;
            }
            Catch(Exception e){
                System.debug('Exception :'+e.getMessage());
            }
        }
    }   
}

 
CharuDuttCharuDutt
Hii Kiran
Try Below Code
trigger NumberOfChild on Account (After Insert,After Update,After Delete) {
	List<Account> accList=new List<Account>();

    Set<Id> setAccIds = new Set<Id>();
    if(Trigger.isInsert){
         if(trigger.isAfter){
        for(Account){
            if(con.ParentId != null){
            setAccIds.add(con.ParentId);
            	}
			}
		}
    } 
    system.debug('setAccIds ==> '+setAccIds);
    if(Trigger.isUpdate){
         if(trigger.isAfter){
        for(Account con : Trigger.new){ 
            if(con.ParentId!=Trigger.oldMap.get(con.Id).ParentId){
               	setAccIds.add(con.ParentId);
                setAccIds.add(Trigger.oldMap.get(con.Id).ParentId);
            	}
          
			}        
        }
    }
    if(Trigger.isDelete){
        if(trigger.isAfter){
        for(Account con : Trigger.old) { 
            if(con.ParentId != null){
            setAccIds.add(con.ParentId);
            	}
        	}
        }
    }    
    for(Account acc :[Select id,Total_ChildAccounts__c,Total_ChildAmount__c ,Description ,(SELECT id,X2020_Revenue__c,Total_Revenue_2021__c FROM  ChildAccounts) from Account where Id in : setAccIds]){
      Integer sum =0;
       
        for(Account Con :acc.ChildAccounts){
            sum+=Con.X2020_Revenue__c;
            system.Debug('s===>'+sum);
            
        }
		acc.Total_ChildAmount__c = sum;
        acc.Total_ChildAccounts__c = acc.ChildAccounts.size();
        
        acclist.add(acc);
    }
    if(acclist.size()>0){
        update accList;     
    }
}
Please Mark It As Best Asnwer If It Helps
Thank You!
AnkaiahAnkaiah (Salesforce Developers) 
Hi Kiran,

Refer the below link have solution for similar kind of ask.
https://salesforce.stackexchange.com/questions/144864/adding-contacts-custom-field-showing-total-on-accounts

If this information helps, Please mark it as best answer.

Let me know if any help required.

Thanks!!
Kiran Hunnaragi 25Kiran Hunnaragi 25
Hi Charu,

Thanks for quick response. I have tried your code and tested however no updated value on the Total Amount field what may be the reason I dont know.

We want total of child account X2020_Revenue__c field and show it  parent account --> Total_Revenue_2020__c field.

_______________________________________________________________________________________________

for(Account acc :[Select id, Total_Revenue_2020__c ,Description ,(SELECT id,X2020_Revenue__c,Total_Revenue_2020__c FROM  ChildAccounts) from Account where Id in : setAccIds]){
      Double sum =0;
       
        for(Account Con :acc.ChildAccounts){
            sum+=Con.X2020_Revenue__c;
            system.Debug('s===>'+sum);
            
        }
        acc.Total_Revenue_2020__c = sum;
        //acc.Total_ChildAccounts__c = acc.ChildAccounts.size();
        
        acclist.add(acc);
    }
    if(acclist.size()>0){
        update accList;     
    }
AnkaiahAnkaiah (Salesforce Developers) 
Hi Kiran,

Below code is working. Please try from your end and let me know if any issues.
trigger Sumofchildaccountssalary on Account (After Insert,After Update,After Delete) {
	List<Account> accList1=new List<Account>();

    Set<Id> setAccIds = new Set<Id>();
    if(Trigger.isInsert){
         if(trigger.isAfter){
        for(Account con : Trigger.new){
            if(con.ParentId != null){
            setAccIds.add(con.ParentId);
            	}
			}
		}
    } 
    system.debug('setAccIds ==> '+setAccIds);
    if(Trigger.isUpdate){
         if(trigger.isAfter){
        for(Account con : Trigger.new){ 
            if(con.ParentId!=Trigger.oldMap.get(con.Id).ParentId){
               	setAccIds.add(con.ParentId);
                setAccIds.add(Trigger.oldMap.get(con.Id).ParentId);
            	}
          
			}        
        }
    }
    if(Trigger.isDelete){
        if(trigger.isAfter){
        for(Account con : Trigger.old) { 
            if(con.ParentId != null){
            setAccIds.add(con.ParentId);
            	}
        	}
        }
    }    
 Map<ID, Account> contactsForAccounts = new Map<ID, Account>([SELECT Id ,parentid, X2020_Revenue__c FROM Account WHERE parentid IN :setAccIds]);
    

Map<ID, Account> acctsToUpdate = new Map<ID, Account>([SELECT Id, Total_Revenue_2020__c FROM Account WHERE Id IN :setAccIds]);

for (Account acct : acctsToUpdate.values()) {
Set<Id> conIds = new Set<Id>();
Decimal totalValue = 0;
for (Account con : contactsForAccounts.values()) {
    if (con.parentid == acct.id && con.X2020_Revenue__c != NULL) {
        totalValue += con.X2020_Revenue__c; 
    }
}
acct.Total_Revenue_2020__c = totalValue;
}
if(acctsToUpdate.values().size() > 0) {
    update acctsToUpdate.values();
}
}

If this helps, Please mark it as best answer.

Thanks!!
Kiran Hunnaragi 17Kiran Hunnaragi 17
Hi Ankhiah,

Thanks for your reply,

I have used your code and would like to inform you, it is only updating previous childs amount on the immidiate parent. Not calculating all childs amount and updating on the parent or grand parent account.

Example: If child account amount field is 20 then immdiate parent Total amount field is showing 20 however on the grand parent it is not calculating both child and parent amount field (Sum) on the grand parent

Child 1 - 20
Parent 1 - 20

Grand total should be 40 on Main parent or Parent Account
AnkaiahAnkaiah (Salesforce Developers) 
Hi Kiran,

The above code is working for  parent records not for grand parents.

Thanks!!
Kiran Hunnaragi 17Kiran Hunnaragi 17
ok, Thank you for your help 

Actually I am looking to sum or calculate all child accounts and show it on main parent account 
Kiran Hunnaragi 17Kiran Hunnaragi 17
Any help on this request will be appreciated.