Activity › Forums › Salesforce® Discussions › How can we count number of contacts associated with accounts?
Tagged: Account Detail, Contact, Contact Record, Count, Person Accounts, Salesforce Customization, Salesforce Development
-
How can we count number of contacts associated with accounts?
Posted by saloni gupta on July 13, 2017 at 12:19 PMSuppose we have a list of account and we want to count the number of contacts associated with each account?
Rahul replied 8 years, 2 months ago 5 Members · 5 Replies -
5 Replies
-
Hello Saloni,
List<Account> acc=[select Name , (Select LastName from contacts) from Account Limit 10];
for(Account acct:acc){
system.debug(‘####’+acct.contacts.size());
} - [adinserter block='9']
-
trigger london1 on Contact (after insert,after delete) {
list li=new list();
if(trigger.isInsert)
{
for(contact c:trigger.new)
{
li.add(c.AccountId);
}list con=[select name,(select id from contacts) from account where id in:li];
for(account acc:con)
{
list c=acc.contacts;
system.debug(‘account:’+acc.name+’Count_of_contact’+c.size());
acc.count_of_contacts__c=c.size();
update acc;
}
}
}this will help you
-
Hi Saloni,
The code for your answer is : –
public class RelatedList
{
public static void ListContact()
{
List accList = [SELECT Name, (SELECT LastName FROM Contacts ) FROM Account];
for(Account acc : accList)
{
System.debug(‘+++’+ acc.contacts.size());
}
}
}-
This reply was modified 8 years, 10 months ago by
shariq.
-
This reply was modified 8 years, 10 months ago by
-
Hi,
simple query :-
SELECT count(Id) FROM Contact Where AccountID=’00141000015cS58′
—Soql query to count total contact related to an account —–List<AggregateResult> results=[SELECT count(Id) FROM Contact Where AccountID=’00141000015cS58′]; //count() return AggregateResult type value
integer total_contact = Integer.valueOf(results[0].get(‘expr0’) + ”);
//integer total_contact=(Integer) results[0].get(‘expr0’);
system.debug(‘total contact of Internal Queries : ‘+total_contact);And trigger to show count on a custom field:
trigger FindContactsCount on Contact (after insert, after update, after delete) {
List<Contact> modContacts = Trigger.isDelete ? Trigger.old:Trigger.new;
Set<Id> accIds = new Set<Id>();
for (Contact c: modContacts) {
accIds.add(c.AccountId);
}
List<Account> modAccounts = [Select Name, (Select Id from Contacts) from Account WHERE Id in: accIds ];for (Account a: modAccounts) {
List<Contact> s = a.Contacts;
System.debug(‘Account:’ + a.Name + ‘ No. of Contacts: ‘+ s.size());
a.No_of_Contacts__c = s.size();
}
}Hope this code will help you and others 🙂
Log In to reply.