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
Davide BreviDavide Brevi 

SOQL relationship aggregate query

Hi to everybody,
I need to aggregate some information from a Parent to Child Relationship Query.

For example, with the following basic query:
SELECT Account.Name,(SELECT Contact.Name FROM contacts) FROM Account

I'd like to count the number of contacts for a specific account.
Is that possible?

Thank you!


 
ShirishaShirisha (Salesforce Developers) 
Hi Davide,

Greetings!

I don't think we can use direct SOQL query to get the count of contacts related to an account.However,you can create the trigger to get the total number using the below sample code:

http://www.sfdcpanda.com/soql-query-counts-number-active-contacts-account-set/

http://www.infallibletechie.com/2013/09/trigger-to-count-number-of-contacts.html

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future.

Warm Regards,
Shirisha Pathuri
Prady01Prady01
Hi there you can try the below query.
 
select count(id) from Contact group by Accountid
Hope this helps!
Prady01
 
Davide BreviDavide Brevi
Thanks Shirisha ,
I can't use a trigger. I need to extract data from workbench...

Best Regards
Davide
Maharajan CMaharajan C
Hi Davide,

If you want the Count of Childs in workbench yes we can do that by using below queries.  

 The below query will count the number of contacts for a specific account  based on the Account Id. 

select AccountId, count(Id) from Contact group by AccountId

If you want to use the Account Name to group the contacts then use the below Query

select Account.Name, count(Id) from Contact group by Account.Name

https://salesforce.stackexchange.com/questions/36690/soql-count-number-of-child-records

Thanks,
Maharajan.C