Set<Id> stAccIds = new Set<Id>(); //Suppose this set has Account Ids
Map<Id,Integer> accountIdWithContactCount = new Map<Id,Integer>();
for(Account acc : [SELECT Id,Name,(SELECT Id FROM Contacts WHERE Active__c = true) FROM Account WHERE Id IN :stAccIds]){
accountIdWithContactCount.put(acc.Id,acc.Contacts.size());
}
Now this map accountIdWithContactCount will have count of contacts for each account
You can get the count by passing account Id Integer count = accountIdWithContactCount.get(accId);
The query to achieve this is: AggregateResult[] groupedResults = [SELECT COUNT(Id) total, AccountId FROM Contact WHERE IsActive = true GROUP BY AccountId];
Try this
Now this map accountIdWithContactCount will have count of contacts for each account
You can get the count by passing account Id
Integer count = accountIdWithContactCount.get(accId);
For relationship Queries refer the below links
https://developer.salesforce.com/blogs/developer-relations/2013/05/basic-soql-relationship-queries.html
http://www.salesforce.com/us/developer/docs/dbcom_soql_sosl/Content/sforce_api_calls_soql_relationships.htm
Regards,
Bhanu Mahesh
AggregateResult[] groupedResults = [SELECT COUNT(Id) total, AccountId FROM Contact WHERE IsActive = true GROUP BY AccountId];