User Story
As a Sales Manager at ABC Corporation, I want to view all Accounts that have at least two related Contacts, so that I can better understand the distribution of Contacts among our Accounts and identify opportunities for building stronger customer relationships. Specifically, I want to retrieve the Account Id and Name fields, along with a related list of up to two Contacts, for all Accounts where there are at least two Contacts associated with the Account. By having access to this information, I can prioritize my sales efforts on Accounts with established relationships, work to deepen these relationships, and ultimately drive sales growth and improve customer satisfaction.
SOQL
List<AggregateResult> acIds = [SELECT AccountId FROM Contact GROUP BY AccountId HAVING COUNT(Id) >= 2];
List<Id> acIdList = new List<Id>();
for (AggregateResult ar : acIds) {
Id accountId = (Id)ar.get('AccountId');
acIdList.add(accountId);
}
List<Account> acList = [SELECT Id, Name, (SELECT Id FROM Contacts LIMIT 2) FROM Account WHERE Id IN: acIdList];
System.debug(acList.size());