function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
pavan kumar 177pavan kumar 177 

Difference in average count roll-up look up relationship

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.

ARPu 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 = 'Customer_Order'].Id;
    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' ) 
        {
            CaseIDs.add(s);
          
        }
    }
    set<Id> setCaseIds = new set<Id>();
    for(Case c : [SELECT Id,ARPU__c,accountId FROM Case WHERE Id IN :CaseIDs]){
        setCaseIds.add(c.AccountId);
    }
    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 group By AccountId];
    Decimal decimalRevenue = 0;
    For(account a1: MList) {
        for (AggregateResult ar : groupedResults) 
        {
        String str = '' + ar.get('aver') ;
        decimalRevenue = Decimal.ValueOf(str) ;
        System.debug('decimalRevenue ::::: ' + decimalRevenue) ;
        a1.ARPU__c  = decimalRevenue;
        }
        Accountstoupdate.add(a1);
    }
    if(Accountstoupdate.size()>0) {
        update Accountstoupdate;
    }
}

I unable to find the problem