Dear Stata colleagues,

I created a loop in order to count the number of dates following 3 conditions (with datetime variables rounded to minutes):

* Condition 1 - datetime1 of all other dates are smaller or equal to datetime1[i] by each date-observation in the sample
* Condition 2 - datetime2 of all other dates is higher or equal to datetime1[i] by each date-observation
* Condition 3 - datetime3 of all other ids is higher or equal to datetime1[i] by each date-observation

I write the following code to meet the pre-conditions and tested for a small sample.
Note: This code does not have moving counting of last 31 days range.

Code:
        
        gen count = .

        local N = _N

        quiet forval i = 1/`N' {
        count if datetime1 <= datetime1[`i']  & datetime2 >= datetime1[`i']  & datetime3 >= datetime1[`i']
        replace count = r(N) in `i'
        }
However, since my sample size has one million observations, I am trying to specify a condition that runs this loop only for the observations in datetime1 which are at the most 31 days before each date-observation analyzed, i.e. datetime1[`i'].

Due to the size of the sample, this loop will be considering all observations in datetime1 by each date in datetime1 analyzed when I only need to be comparing with date-observations in the prior 31 days.

Any advice or suggestion on how can I tackle this issue would be much appreciated.

Thank you in advance,