+ Start a Discussion
Deepak agarwal 9Deepak agarwal 9 

get opportunities count for each account soql

i want opportunities count for each account using soql.
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),
							  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!