+ Start a Discussion
Amit Jadhav 13Amit Jadhav 13 

how To Write Aggregate Functions In visualforce page

My requirement is Display Avg IN Visualforce page 
Field Is a Quantity__c so Show the Average Of Quantity 
Deepali KulshresthaDeepali Kulshrestha
Hi Amit,
The AggregateResult object is like a Map and so to access the values you need to use map syntax in the Visualforce:
<apex:column value="{!s['total']}"></apex:column>

You can use the map syntax as follows:
<apex:page controller="MyController">
    <apex:pageBlock>
        <apex:pageBlockTable value="{!results}" var="r">
            <apex:column value="{!r['aaa']}"/>
            <apex:column value="{!r['bbb']}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>

public with sharing class MyController {
    public AggregateResult[] results {
        get {
            return [select AccountId aaa, count(Id) bbb from Contact group by AccountId];
        }
    }
}


I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha 
Amit Jadhav 13Amit Jadhav 13
Hey Deepali 
Thanks For Replying
But My Query Like That
List<Id> ProdCodes = new List<Id>();
     oppList=[Select opportunity.id from order where id=:ord.id];
     system.debug('oppid'+oppList);
     for(Order o : oppList)
     {
      ProdCodes.add(o.opportunity.id);
     }
     AggregateResult[]  results=[select AVG(Unit_Price_UOM__c)avg from Cost_Price__c where Opportunity__c IN:ProdCodes]; 
Deepali KulshresthaDeepali Kulshrestha
Hi Amit,

In your query, you have assigned the name to AVG and you haven't been getting the value from the query. Please change your 
query from :
  AggregateResult[]  results=[select AVG(Unit_Price_UOM__c)avg from Cost_Price__c where Opportunity__c IN:ProdCodes]; 
to:
  AggregateResult[]  results=[select AVG(Unit_Price_UOM__c)avg from Cost_Price__c where Opportunity__c IN:ProdCodes]; 
Object avgAmount = results=[0].get('avg');

For more information rregarding this please go thorugh the following link:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL_agg_fns.htm

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha