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
Pritam Patil 19Pritam Patil 19 

How to retrieve count of child record using parent record based on time(Current Month & Last Month)

Hello,

I have a child object "Website_Visit_Clickpath__c" and parent object "Lead_Inspector__c". I want to retrieve the count of child records using the parent through a trigger based on time, i.e. the records of the current month and records of the last month.

Below is the code I am using :

trigger WebsCount on Website_Visits_Clickpath__c (after insert,after update) {

    List<Lead_Inspector__c> leadInspector=new List<Lead_Inspector__c>();
    
    Website_Visits_Clickpath__c wCount;
    Lead_Inspector__c lIns;

    Integer mnth = System.Today().Month();
    
    system.debug('****Month******'+mnth);
    
    Integer Prevmnth = (System.Today().Month())-1;
    
    system.debug('****PrevMonth******'+Prevmnth); 
    
    Integer yr = System.Today().Year();
    
    
    Integer e=0;
    Integer p=0;
    List<id>LeadInspectorIds = new List<Id>();

    for(Website_Visits_Clickpath__c u:Trigger.New){
        if(u.id!=null){
        
           if(u.Lead_Inspector__c!=null)
            {
              LeadInspectorIds.add(u.Lead_Inspector__c) ;
              
            }  
            system.debug('*********Test*********'+LeadInspectorIds);
            wCount= [SELECT Id,Lead_Inspector__c FROM Website_Visits_Clickpath__c WHERE Id=:Trigger.New];
            lIns=[SELECT Id,Total_Website_Visitors_CM__c,Total_Website_Visitors_LM__c,WebVisitorDiff__c, Total_Lead_Identified__c FROM Lead_Inspector__c WHERE Id=:wCount.Lead_Inspector__c];
             
            system.debug('+++++++++++++wCount+++++++++'+wCount); 
            system.debug('+++++++++++++lIns+++++++++'+lIns); 
                                
            e = [select count() from Website_Visits_Clickpath__c where Lead_Inspector__c =:wCount.Lead_Inspector__c  AND  CALENDAR_MONTH(Date_Time__c) = :mnth AND CALENDAR_YEAR(Date_Time__c) = :yr];
            
            p = [select count() from Website_Visits_Clickpath__c where Lead_Inspector__c =:wCount.Lead_Inspector__c  AND  CALENDAR_MONTH(Date_Time__c) = :Prevmnth AND CALENDAR_YEAR(Date_Time__c) = :yr];
            
           
               
            lIns.Total_Website_Visitors_CM__c=e;
            
            lIns.Total_Website_Visitors_LM__c=p;
            
            lIns.WebVisitorDiff__c=e-p;
            
            system.debug('+++++++++++++lIns.WebVisitorDiff__c+++++++++'+lIns.WebVisitorDiff__c);
            
            leadInspector.add(lIns);
            
 
        }
        
            update leadInspector;
        
     }

}


Thanks.