Roll Up Summary Triggers on LookUp Relationship

Generally we can create rollup summary fields in between Master_Detail relationship.
if we want to create roll up summary  fields in between look up relation we need to  write a trigger.

Requirement :-
Custom field On contact :Salary__C
Custom field on Account :Total_salary__C

Count the sum of  salaries of contact with same AccountId  and the sum will be reflected on that Account

trigger calTotalSalOnAccoun on contact(after update,after insert)
 set<id>AccountIds = new set<id>();
 List<Account> accountsToUpdate = new list<account>();
 for(contact con : Trigger.New)


for(AggregateResult ar:[select AccountID, SUM(salary__C) maxsal from contact where AccountID in:AccountIds GROUP BY AccountId] )
 Account a = new Account(Id = (Id)ar.get('AccountId'));



update accountsToUpdate;


count the number of contacts under an  Account

trigger countNumberOfContacts on Contact (after insert,after update) {
  Set<id>AccountIds = new Set<ID>();
  List<account> AccoutsToUpdate = new list<Account>();
  for(contact con:
  for(AggregateResult ar:[select AccountId,Count(Id) NoOfContacts from contact where AccountId In:AccountIds Group By AccountId])
        Account a = new Account(Id = (Id)ar.get('AccountId'));
      Update AccoutsToUpdate;



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s