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
Salesforce BlitzSalesforce Blitz 

get top 5 accounts based on sum of related opportunity field data in salesforce

Hi guys,

I have custom opportunity field named Total_Amount__c.
I need to get Top 5 accounts with opportunities based on Total Amount.
Need to code above(not in reports)

Note: Consider if an account have 5 opps, then the sum of 5 opp fields need to be taken into consideration.

Thanks in advance,
prasanth kumarprasanth kumar
hi ,  here is the code.  If it is not suitable then reply me back.  

i created one rollup summary field on account for opportunity called   total_opportunity_amount__c

public class topfiveaccounts {
 public list<account> acc{set;get;}
 public topfiveaccounts()
 acc=new list<account>();
 acc=[select id,name,total_opportunity_amount__c from account order by total_opportunity_amount__c desc limit 5];

<apex:page controller="topfiveaccounts">
<apex:pageblock >

<apex:pageblocktable value="{!acc}" var="a">
<apex:column value="{!}" />
<apex:column value="{!a.total_opportunity_amount__c}" />

Thiyagarajan Selvaraj (SFDC Developer)Thiyagarajan Selvaraj (SFDC Developer)
Hi Laxman, 

You should get top 5 accounts based on sum of related opportunity field using the following query 

List<AggregateResult> aggregateResults = [SELECT AccountId, SUM(Total_Amount__c) FROM Opportunity GROUP BY AccountId ORDER BY SUM(Total_Amount__c) DESC LIMIT 5];

Thiyagarajan Selvaraj