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
Answer plzAnswer plz 

Query top 15 records with Maximum child records

I have a task to do. For hat I have to fetch top 15 records with maximum number of child records. So can anyone tell me How to query a parent record which has maximum number of child records associated  ? 
CharuDuttCharuDutt
Hii User1234
Create a Rollup Summary field on parent Object

Write a query like:
Total_Opportunities__c = Rollup Summary Field On Account Which Shows Number Of Opportunites Associated With Account Record 

SELECT Id, Name, Total_Opportunities__c FROM Account  ORDER BY Total_Opportunities__c DESC
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.
 
Please Mark It As Best Answer If It Helps
Thank You!
Suraj Tripathi 47Suraj Tripathi 47

Hi,

You can write either trigger or rollup summary to get the required result as you want.

Trigger

trigger CountContactOnAccount on Contact (after INSERT, after UPDATE, after DELETE ) {
Set <Id> accountIds = new Set <Id>();
List <Account> lstAccountsToUpdate = new List <Account>();
 if(Trigger.isInsert){
    for(Contact con:trigger.new){
        accountIds.add(con.accountID);
    }
}
if(Trigger.isUpdate|| Trigger.isDelete){
    for(Contact con:trigger.old){
        accountIds.add(con.accountID);
    }
}

for(Account acc:[SELECT Id,Name,Count_Contact__c,(Select Id from Contacts) from Account where Id IN: accountIds]){
    Account accObj = new Account ();
    accObj.Id = acc.Id;
    accObj.Count_Contact__c = acc.Contacts.size();
    lstAccountsToUpdate.add(accObj);
}

UPDATE lstAccountsToUpdate;
}

 

After That you can query

List<Account> accountList=new List<Account>();
accountList=[Select id,Count_Contact__c from Account ORDER BY Count_Contact__c DESC limit 15 ];

 

Please mark it as Best Answer so that other people would take references from it thanks

or write Rullup summary

 

 

Create a Roll-Up field on Account object to count the number of Contacts added to it

Create a number field 
In Salesforce Classic

Click on Setup.
Under Customize, expand Accounts by clicking the button beside it.
Click on Fields.
Scroll down and on the Account Custom Fields & Relationships, click on New.
Select Number as the type and click on Next.
Add the details. Enter Counter for the name and 18 for the Length
Input 0 for the Default Value.
Click on Next.
Select the profiles who can access this field.
Click on Next.
Select the page layouts and click on Save.
In Lightning Experience 
Click on the gear icon.
Click on Setup.
Click on Object Manager and click on Accounts.
Click on Fields and Relationships.
Click on New.
Select Number as the type and click on Next.
Add the details. Enter Counter for the name and 18 for the Length.
Input 0 for the Default Value.
Click on Next.
Select the profiles who can access this field.
Click on Next.
Select the page layouts and click on Save.
 
Create a Process Builder
In Salesforce Classic
Click on Setup.
Under Create expand Workflow Rules & Approvals by clicking the button beside it.
Click on Process Builder.
Click on New.
Enter the Name and Description.
For the 'The process starts when*,' select A record changes.
Click on Save.
Click on Add Object.
Select Contact.
Select only when a record is created.
Click on Save.
Click on Add Criteria.
Enter the Criteria Name.
Select Formula evaluates to true.
On the formula field, enter True.
Click on Save.
Click on Add Action.
For the Action Type, select Update Records.
Enter the Action Name.
Click on Select Record to Update.
Choose Select a record related to the Contact.
Click on the Type to filter list field and look for Account ID.
Click on Choose.
Under 'Set new field values for the records you update,' click on Find a field and look for the field we created a while ago and click on it.
For the Type, click on Formula.
Click on Build a formula.
Enter [Contact].Account.Counter__c + 1 on the formula field.
Click on Use this Formula.
Click on Save.
Click on Activate.

Please let me know with trigger it is working or not??

Please mark it as Best Answer so that other people would take references from it.

Thank You

srinusrinu
Hi User1234,
Greetings to you!

Step -1:-  Creating Rollup Summary filed on Parent Object.

Step - 2:-  Write a query  like this
 
[SELECT id, Fields FROM Parent_Object__c ORDER BY Rollup_Summary_Field__c DESC LIMIT 15];
 
  • It will return the top 15 parent records having child records count in Descending Order.
Note: This will work if objects have a master-detail relationship.


I hope it helps you.

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. It will help to keep this community clean.

Thanks and Regards,
Srinu

 
Harshit Singh 5Harshit Singh 5
Hi User1234,

QUERY = [SELECT COUNT(Id), AccountId FROM Contact GROUP BY AccountId Order By COUNT(Id) DESC LIMIT 15]

This will get you top 15 accounts with maximum child records as requested.

Please mark it as Best Answer so that other people would take references from it.
Thank You