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

Doing Calculations in APEX

Hi All,


My goal is to be able to have my Class grab a list of Task Records (which I know how to  do), perform a very simple calculation on them (which I do not know how to do) and then have the result be dropped into a field on the related Lead Record (which I know how to do). Would someone please help me understand how to perform simple calculations with the results of the query in my class or put me in the direction of documentation that might help? Thanks.


In case this helps, I am trying to create a 'Response Rate' field on the Lead Object. I want to look at all the Completed Tasks related to each Lead Record, then, grab all of the Task Records where the Type equals 'Email Sent' and 'Email Reply'. I woud then like to divide the number of Tasks where the Type is 'Email Sent' by the number of Tasks where the Type is 'Email Reply' and put that percentage into a field on the Lead called 'Response Rate'. 


I would make it a static method, just for reusabilities sake and pass it a list of lead ids, then query for the tasks for those leads and then bucket the totals for the two tasks types. Then return a map of Id's to decimals for the calculation you want to perform. 


public static Map<Id,Decimal> getResponseRate(List<Id> lead_ids){
	Map<Id,Decimal> response_rates = new Map<Id,Decimal>(); 
	Map<Id,Integer> email_sent = new Map<Id,Integer>(); 
	Map<Id,Integer> email_reply = new Map<Id,Integer>(); 

	for(Id l : lead_ids){

	Integer temp_sent; 
	Integer temp_reply;
	for(Task t : [SELECT Status,WhoId FROM Task WHERE WhoId IN :lead_ids AND (Type = 'Email Sent' OR Type = 'Email Reply')]){
		if(t.Type == 'Email Sent'){
			temp_sent = email_sent.get(t.WhoId); 
		if(t.Type == 'Email Reply'){
			temp_reply = email_reply.get(t.WhoId); 

	for(Id lid : lead_ids){

	return response_rates; 


Puneet SardanaPuneet Sardana



This can be accomplished using SOQL,



AggregateResult [] aggr1=[SELECT Lead.Id,COUNT(Id)

                                         FROM Task

                                         WHERE Who.Type='Lead'

                                         AND Type='Email Sent'

                                        GROUP BY Lead.Id];


AggregateResult [] aggr2=[SELECT Lead.Id,COUNT(Id)

                                         FROM Task

                                         WHERE Who.Type='Lead'

                                         AND Type='Email Reply'

                                        GROUP BY Lead.Id];


The final calculation is loop through the result of the query and do aggr1[i]/aggr2[i] for the same lead id.


Please fill in the appropriate fields in the query.