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
Deepak agarwal 9Deepak agarwal 9 

get opportunities count for each account soql

Hi
i want opportunities count for each account using soql.
badibadi
Try this

SELECT COUNT(Id), AccountId, Account.Name FROM Opportunity GROUP BY AccountId, Account.Name
UC InnovationUC Innovation
The simplest way is to use SOQL Aggregate Functions (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL_agg_fns.htm). A specific example for your case is below:
 
AggregateResult[] oppcount = [SELECT COUNT(Id),
									 AccountId
							  FROM Opportunity
							  GROUP BY AccountId];

The results can be accessed in a similar way to this:
 
// The​ count can be accessed like this									  
for (AggregateResult parentAccount : oppcount) {			
	Id accountId = (Id)parentAccount.get('AccountId');
	Integer numberOfOpps = (Integer)parentAccount.get('expr0');
			
	system.debug('This is the parent account Id: ' + accountId);
	system.debug('This is the number of related opportunites: ' + numberOfOpps);
}

Hope this helps!

AM