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
r nareshr naresh 

how find aggregate function avg(amount) from opportunity

im getting error in vf if i use the compaign id as value of column .
apex cls
-----------------
public integer avg{get;set;}
  list<AggregateResult> lAGR{get;set;}
  public exampleongroupby()
  {
   lAGR=[select campaignid,AVG(amount) avg from Opportunity group by campaignid];
  }
   public list<opportunity> getResult() 
   {
      list<opportunity> opp=new list<opportunity>();
      for(AggregateResult agr:lAGR)
      {
        opportunity op=new opportunity(agr);
        opp.add(op);
      }
        return opp;
   }
   class opportunity
   {
   public integer avg{get;set;}
     public opportunity(AggregateResult agr)
     {
      
     }
   }
}
vf page
------------
<apex:page controller="exampleongroupby">
  <apex:form >
    <apex:pageblock title="Test For AVG,COUNT(),COUNT_DISTINCT,MAX,MIN,SUM">
       <apex:pageBlockTable value="{!Result}" var="aar">
        
         <apex:column value="{!aar.avg}"/>
       </apex:pageBlockTable>
    </apex:pageblock>
  </apex:form>
</apex:page>


thank u in advance
Zuinglio Lopes Ribeiro JúniorZuinglio Lopes Ribeiro Júnior
Hello,

Try the code below:

Class:
public with sharing class exampleongroupby {

	public Integer avg { get; set; }
	List<AggregateResult> aggregateResults { get; set; }
	
	public exampleongroupby() {
		aggregateResults = [SELECT CampaignId, AVG(Amount) avg FROM Opportunity GROUP BY CampaignId];
	}
   
	public List<opportunity> getOpportunities() {
      
		List<Opportunity> opp = new List<Opportunity>();
      
		for (AggregateResult agr: aggregateResults)
		{
			opportunity op=new opportunity(agr);
			opp.add(op);
		}
		return opp;
	}
   
	public class Opportunity {
		
		public Integer avg { get; set; }
		
		public Opportunity(AggregateResult agr) {
			avg = Integer.valueOf(agr.get('avg'));
		}
   }
}

VF: 
 
<apex:page controller="exampleongroupby">
    <apex:form >
        <apex:pageblock title="Test For AVG,COUNT(),COUNT_DISTINCT,MAX,MIN,SUM">
            <apex:pageBlockTable value="{!opportunities}" var="opp">
                
                <apex:column headerValue="AVG" value="{!opp.avg}"/>
            </apex:pageBlockTable>
        </apex:pageblock>
    </apex:form>
</apex:page>

You forgot to set the value in your Opportunity contructor class: 
 
public Opportunity(AggregateResult agr) {
			avg = Integer.valueOf(agr.get('avg'));
		}

Regards.

Don't forget to mark your thread as 'SOLVED' with the answer that best helps you.