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
ElkayElkay 

SOQL - Top 3 Opportunity records per Account

Hello Everyone,

I want to extract the top 3 opportunity records for each account based on the Amount Value. I am trying to create a SOQL query but unable to fetch only 3 records per group.

Help Please....

Thank you...
Elkay

logontokartiklogontokartik
Hi Elkay,

Can you try this query 

List<Account> acctWithOpportunities = new List<Account>();

acctWithOpportunities = [Select id, Name, (Select Id, Name, Amount from Opportunities order by Amount desc LIMIT 3) from Account];

for(Account acc : acctWithOpportunities){
 
   for(Opportunity opp : acc.Opportunities){
        system.debug('Opp Name ' + opp.Name);
        system.debug('Opp Amount ' + opp.Amount);
   }

}

Thank you