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)
 {
 AccountIds.add(con.AccountId);

}

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'));

a.total_salary__C=(Decimal)ar.get('maxsal');
 accountsToUpdate.add(a);

}

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: trigger.new)
  {
   AccountIds.add(con.AccountId);
  }
   
  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'));
        a.number_of_contacts__c=(Decimal)ar.get('NoOfContacts');
        AccoutsToUpdate.add(a);
        
      }
      
      Update AccoutsToUpdate;
      
     }

 

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s