-2

I have 2 custom objects Parent__c and Child__c. Which is having look-up relationship. How to calculate COUNT, SUM, MIN, MAX using trigger? I have the below code which can only SUM, But I want COUNT, SUM, MIN, MAX.

trigger UpdateAmount on Opportunity (after insert, after update) {
    set<id> ids=new set<id>();
    for(opportunity opp: trigger.new)
    {
        ids.add(opp.AccountId);
    }    
    list<Account> acc=[select id,Total_Amount__c from account where id in:ids];
    list<opportunity> op=[select id, amount from Opportunity where AccountId in:ids];
    for(Account a:acc)
    {
                  decimal sum=0;
       for(opportunity o:op )
       {
           sum=sum+o.amount;
       }
        a.Total_Amount__c=sum;
    }
update acc;
}
3

Aggregate functions in SOQL, such as SUM() and MAX(), allow you to roll up and summarize your data in a query. For more information on aggregate functions click,

trigger UpdateAmount on Opportunity (after insert, after update) {
    set<id> ids=new set<id>();
    for(opportunity opp: trigger.new)
        ids.add(opp.AccountId);

    List<Account> accountsToUpdate=new List<Account>();
    Map<ID, Account> acc = new Map<ID, Account>([select id,Total_Amount__c from account where id:=ids]);
    AggregateResult[] groupedResults = [SELECT AccountId,SUM(Amount)amt FROM Opportunity where AccountId in:ids group by AccountId];

    for(AggregateResult Results: groupedResults){
         Id accountId =(id) Results.get('AccountId');         
         Account a=acc.get(accountId);
         a.Total_Amount__c=(integer)Results.get('amt');;
         accountsToUpdate.add(a);
    }    
  update accountsToUpdate;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.