AggregateResult in Salesforce

AggregateResult in Salesforce is used to find Sum, Min, Max and Avg. It is similar to Aggregate function in SQL.

Using Aggregate Result, we cannot fetch data. It is mainly used to find Sum, Min, Max and Avg.

Sample Code:

Visualforce page:

<apex:page controller="Sample" sidebar="false" action="{!show}">
<apex:pagemessages />
<apex:form >
    <apex:pageBlock >
        <apex:pageblockTable value="{!SummaryList}" var="r">           
            <apex:column headerValue="Account Name" value="{!r.AcctName}"/>
            <apex:column headerValue="Number of Contacts" value="{!r.Total}"/>
        </apex:pageblockTable>
    </apex:pageBlock>
</apex:form>
</apex:page>

Apex Controller:

public with sharing class Sample {
    public List<AggregateResult> Result {get;set;}   
    public List<Summary> SummaryList {get;set;}
    public List<Account> AcctList;
    public Map<Id, Account> IdAccount;
    List<Id> Ids;
   
    public void show() {
        SummaryList = new List<Summary>();
        Result = new List<AggregateResult>();
        Ids = new List<Id>();
        AcctList = new List<Account>();
        IdAccount = new Map<Id, Account>();
       
        Result = [SELECT Count(Id) Total , AccountId FROM Contact WHERE AccountId != null GROUP BY AccountId];              
       
        for(AggregateResult a : Result) {  
            Ids.add((Id)a.get('AccountId'));
        }
       
        AcctList = [SELECT Name FROM Account WHERE Id IN : Ids];
       
        System.debug('Account List' + AcctList);
       
        for(Account a : AcctList) {
            IdAccount.put(a.Id, a);           
        }
       
        System.debug('Ids and Accounts are ' + IdAccount);
               
        for(AggregateResult a : Result) {
            Account TempAcct = new Account();           
            TempAcct = IdAccount.get((Id)(a.get('AccountId')));
            system.debug('Account Name is ' + TempAcct.Name);
            SummaryList.add(new Summary(a, TempAcct.Name));               
        }   
    }
   
    public class Summary {
        public Integer Total {get;set;}
        public String AcctName {get;set;}
       
        public Summary(AggregateResult a, String AccountName) {
            Total =  (Integer)a.get('Total');
            AcctName = AccountName;
        }
    }
}

Output:

Leave a Reply