Fetch Total Related List Record on Parent With MAX Salary in Apex Salesforce

APEX

This blog will help to calculate Number of Employees with Max Salary from Employee on Account record. For this approach i have used aggregate method to get MAX salary and use Count for number of employee.

Apex Trigger:- EmployeeInfo

trigger EmployeeInfo on Employe__c (After insert, After Update, After Delete, After Undelete) {

    List<Employe__c> empList = Trigger.isDelete?Trigger.Old:trigger.New;

    Set<Id> accIds = new Set<Id>();
    for(Employe__c emp : empList){
        if(emp.Account__c != null){
            accIds.add(emp.Account__c);
            if(Trigger.IsUpdate){
                // below criteria will check if user change the parent like Account then Calculation will update on Old Parent
                if(trigger.OldMap.get(emp.Id).Account__c != emp.Account__c ){
                    accIds.add(trigger.OldMap.get(emp.Id).Account__c);
                }
            }
        }
        	
    }   
    
    
    AggregateResult[] agrResult = [Select Account__c, COUNT(Id)totalEmp, Max(Salary__c)MaxSal from Employe__c Where Account__c IN: accIds
                                         GROUP BY Account__c];
    Map<Id, Account> accMap = New Map<Id, account>([Select Max_Salary__c,Total_Employee__c From Account Where Id IN: accIds]);

    for(AggregateResult agr : agrResult){
        accMap.get((Id)agr.get('Account__c')).Max_Salary__c = (Decimal)agr.get('MaxSal');
        accMap.get((Id)agr.get('Account__c')).Total_Employee__c = (Integer)agr.get('totalEmp');
    }
    if(accMap.size() > 0)
        update accMap.values();    
}

Leave a Reply