In this blog we show how to implement roll-up summary on lookup relationships in Salesforce. This can add immense value to business users by providing useful information at the right place and improve usability and adoption.
First, let us look at the two types of relationships in Salesforce.
Roll-Up summary field can be created on Master (Parent) record to summarize (Count, Min, Max, Sum) the related Detail (Child) records. This feature is available out-of-the-box. You can read more about it here.
It is not possible to make every relationship a Master-Detail relationship and leverage the roll-up summary formulas due to following reasons:
The below example shows you how to implement Roll-Up Summary on a Lookup relationship using Apex trigger and Collections.
Let us consider two simple business scenarios
Scenario 1: All users with access to a Quote should be able to see the total value of a quote across all quote line items. Quote-Quote Line Item is a Master-Detail relationship, so the out of the box roll-up functionality can be used to implement this.
Scenario 2: The Sales VP wants to see the total quoted amount on every account across all quotes made for that account. The VP can use this information as a quick reference to the total opportunity value of an account without going to multiple screens and reports.
Now, Account-Quote is a lookup relationship and the out of the box roll-up functionality cannot be used. The Quoted_Opportunity_Amount__c parameter on Account object should auto calculate the sum of GrandTotal from all the Primary Quotes across opportunities for that account.
Implementing roll-up summary for lookup relationships (Scenario 2)
Create a Trigger on Quote object for all operations (Insert, Update, Delete, Undelete). So, whenever a Quote record is touched it will recalculate the summary field on the related Account Object.
Objects and Fields used
Standard Objects: Account and Quote
Custom Fields: Quoted_Opportunity_Amount__c (on Account)
Standard Field for Calculation: GrandTotal, IsSyncing (on Quote)
Remember to write unit tests before you deploy. You may change the actual summary operation (Count, Min, Max, Average) based on the type of Roll-Up summarization you need.