Skip to main content
Antonino Cupi (Edreams Odigeo) 님이 #Apex에 질문했습니다
Hi all,

I have to calculate the average of a field A, the problem is that I need to calculate the average of the 5 records on top of it and the 5 records under it ordered by another field B.

For example:

I need to calculate the avg of the field A of the record A taking in consideration the 5 records on top of it and under it ordered by the field B

Record     Field A Value      Field B Order By     

1               3,0                      10

2               4,0                       9

3               1,0                       8

4               12,0                     7

5               7,0                       6

A               AVG(?)                5

6              3,0                        4

7              4,0                        3

8              4,0                        2

9              5,0                        1

10            1,0                        0

How can I create this logic?

Thanks
답변 5개
  1. 2019년 3월 20일 오후 2:24
    Hello Anotnino,

    This will work dynamicaly for whatever the list size is but only takes top 5 and bottom 5 of the record A assuming record A is located at the center of the list. therefore, its always average of 10 numbers.

    list<objecttype> recordsfetched=new list<objecttype>();

    recordsfetched=[select fieldA,FieldB from object order by FieldB desc];

    integer sumoftopfivenumbers=0;

    integer sumofbelowfivenumbers=0;

    integer avg=0;

    integer mid=0;

    if(recordsfetched.size()!=NULL&&recordfetched.size()>=10){

    //deciding on the position of Record A based on size of list

    if(recordsfetched.size()%2==0){

    mid=recordsfetched/2;

    }

    else{

    mid=(recordsfetched+1)/2;

    }

    //calculates sum of top 5 numbers of A record

    for(integer i=mid-1;i<=mid-5 ;i--){

    sumoftopfivenumbers=(recordsfetched[i].fieldA)+sumoftopfivenumbers;

    }

    //calculates sum of bottom 5 numbers of A record

    for(integer i=mid+1;i<=mid+5;i++)

    {

    sumofbelowfivenumbers=(recordsfetched[i].fieldA)+sumofbelowfivenumbers;

    }

    //calculates average of top 5 and below 5 of record A

    avg=(sumoftopfivenumbers+sumofbelowfivenumbers)/10;

    //places average value in fieldA which is the mid value of the list

    recordsfetched[mid].feildA=avg;

    }

    Hope this helps, Mark it as solved if it did.

    Thanks,

    Sarvani

     
0/9000