+ Start a Discussion
Neha Kumari 86Neha Kumari 86 

write a query to get parent with max no of child records?

write a query to get parent with max no of child records?
NagendraNagendra (Salesforce Developers) 
Hi Neha,

You can achieve in this simple way:-

Create a Rollup Summary field on parent Object

Write a query like:
[SELECT id, desired_field__c FROM Parent_Object__c ORDER BY Rollup_Summary_Field__c DESC LIMIT 10];
It will return top 10 parent records having child records count in Descending Order.

Note: This will work if objects have a master-detail relationship.

Hope this resolves the issue.

Kindly mark this as solved if the information was helpful.

Thanks,
Nagendra
Deepak Kumar SharmaDeepak Kumar Sharma
Hi Neha,
If you only want to get the number of child records corresponding to parent record then you can also try the below one :-

List<String> LiStr = new List<String>();
for(Account acc: [select Id,name from Account]){
    LiStr.add(acc.id);
}
List<AggregateResult> Result = [select Count(Name)cnt, AccountID from contact where Accountid In: LiStr group by Accountid];
system.debug('LiCon--->'+Result);
For(AggregateResult rs : Result){
    system.debug('Account ID--->'+rs.get('AccountID'));    
    system.debug('number of Contacts--->'+rs.get('cnt'));    
}

Happy Coding!!! :)