What is the best way to get the number of childrecords on a personaccount with the PersonContactId as Id field, the lookup being a contact lookup?

I have the object Newsletter, with a contact lookup field and want a SOQL which gives me personaccounts with the number of related newsletter.

I tried: [SELECT ID, PersonContactId, (SELECT Id FROM Newsletter__r) FROM Account], but it only tells me that it doesnt understand the relationship.

I also tried getting the it with a separate SOQL: [SELECT Id, count(Id) FROM Newsletter__c WHERE ContactId__c in :setPersonAccounts], but I get the error "Field must be grouped or aggregated: Id" and if I group by id I get the error "Grouped field should not be aggregated: Id".


You can use like that .just used Newsletter__r( child relationship name )

List AccountList = [SELECT Name, (SELECT id FROM Newsletter__r) FROM Account]; for (Account Acc: AccountList ) { // do something with it... Acc.Newsletter__r.size(); }

| improve this answer | |
  • (SELECT id FROM Newsletter__r) isnt working. The Relationship is a lookup from custom object to contact. Salesforce seems to not understand that i want to reference personaccounts. – Tim Werner Apr 22 at 17:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.