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
Sana123Sana123 

Count Number of contacts by using aggregate SOQL

I have to count Number of contact according to a picklist field value.
i have a picklist field in contact object which has two value - yes and No ,..i have to count those number of contact which ha yes and no and popultate the counting to account's two custom fields --  total_no_yes__c = count no of contact has yes......
total_no__c = count no of contact has no.....
Using SOQl aggregate
Suraj Tripathi 47Suraj Tripathi 47


Hi Please find the solution. "Count Number of contacts "

Public static void data(){
        List<Contact> contactList=new List<Contact>([Select id,active__c,AccountId from Contact where AccountId!=null]);
        Set<Id> accountSet=new Set<Id>();
        
        
        map<Id,List<Contact>> mapYes=new map<Id,List<Contact>>();
        map<Id,List<Contact>> mapNo=new map<Id,List<Contact>>();
        
        for(Contact con:contactList){
            accountSet.add(con.AccountId);
            if(con.active__c=='Yes'){
                
                if(!mapYes.containsKey(con.AccountId)){
                    List<Contact> conList=new List<Contact>();
                    conList.add(con);
                    mapYes.put(con.AccountId,conList);
                }else{
                    List<Contact> conList=mapYes.get(con.AccountId);
                    conList.add(con);
                    mapYes.put(con.AccountId,conList);
                }
                
            }else if(con.active__c=='No'){
                
                
                if(!mapNo.containsKey(con.AccountId)){
                    List<Contact> conList=new List<Contact>();
                    conList.add(con);
                    mapNo.put(con.AccountId,conList);
                }else{
                    List<Contact> conList=mapNo.get(con.AccountId);
                    conList.add(con);
                    mapNo.put(con.AccountId,conList);
                }
                
            }
        }
        system.debug('mapYes:::'+mapYes);
         system.debug('mapNo:::'+mapNo);
        List<Account> accountList=new List<Account>([Select Id,total_no_yes__c,total_no__c from Account where id in: accountSet]);
        for(Account ac:accountList){
            ac.total_no_yes__c=mapYes.get(ac.Id).size();    
            ac.total_no__c=mapNo.get(ac.Id).size();
        }
        update accountList;
    }
Please let me know it is working or not?
Please mark it as the Best Answer if it helps you.
Thank You

 

Sana123Sana123
Hello..
can you please help me to write this code for trigger helper class.