I got a requirement like to calculate average in account based on particular record type of case. My requirement is:

I have a field called ARP in account currency. I want to calculate overall average of ARP field in particular record type called customer order whether Case details either new or add-on.

So I'm trying write a trigger a trigger.

BARP field in case is a formula currency data type.In account also i had created Arpu name with currency(5,2).

But i am getting a difference in average.

For sample scenario: 41.51 & 94.51

Actual average for above scenario like 67.5.But, i am getting 139.51

trigger ForARPU on case (after delete, after insert) 
Id recordTypeId = [Select Id From RecordType Where DeveloperName = 
List<Account> Accountstoupdate =new List<Account>();
List<Case> CaseIDs = new List<Case>();
for (Case s : Trigger.new)
    if(s.RecordTypeId == recordTypeId && s.Case_Details__c =='New 
                                  Subscription' || s.Case_Details__c =='Add On' ) 

set<Id> setCaseIds = new set<Id>();
for(Case c : [SELECT Id,ARPU__c,accountId FROM Case WHERE Id IN :CaseIDs]){
List<Account> MList = [select Id,name,ARPU__c  from Account where id =:setCaseIds];
List <aggregateResult> groupedResults = [select sum(ARPU__c)aver from case where AccountId =: MList];
Decimal decimalRevenue = 0;
For(account a1: MList) {
if(groupedResults.size() > 0) 
    String str = '' + groupedResults[0].get('aver') ;
    decimalRevenue = Decimal.ValueOf(str) ;
    System.debug('decimalRevenue ::::: ' + decimalRevenue) ;
    a1.ARPU__c  = decimalRevenue;
if(Accountstoupdate.size()>0) {
    update Accountstoupdate;

Please can anyone tell me where did i went to wrong side


Here if you don't get any results in query then you will get exception

Account M = [select Id,name,ARPU__c  from Account where id =:setCaseIds];

You should use it as

List<Account> MList = [select Id,name,ARPU__c  from Account where id =:setCaseIds];

also as you are passing set of Id so you will get multiple results so assign this to list.

  • Thanks It works fine.For sharing knowledge.But i didn't get actual average.There is a difference in average.@Tushar Sharma
    – Pavan tej
    Sep 27 '16 at 16:36
  • @Pavantej you can post another question for that. If it solves your problem you can accept thhis answer. Sep 27 '16 at 16:37

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.