Hi everyone, just upfront: I am pretty new to Stata so please excuse certain rookie mistakes that might occur.

I have a long format dataset showing patients with their date of surgery and postoperative pain scores taken at postoperative visits (in no strict intervals).
The variable for the pain scores is labeled score_pain_* (* being the number of the visit up to 50), I already created a variable showing the time between surgery and the visit in days time_surgerytopainscore* (* again being the number of the visit up to 50).

Now I want to find the patients who reported a pain score of 3 or lower consecutively over any interval equal to or bigger than 3 months (91.3125 days).

So I put together the following code with i being the first visit where a score =< is reported and j any score <= after 3 months or more. However I want to exclude the patients who reported a score higher than 3 in between those visits i and j.
The option with k I tried includes patients who report a score <=3 at any visit in between i and k but that does not solve my problem of excluding those patients who report anything higher (there might be multiple visits in between i and j) and it excludes the patients who did not have any visits in between i and j.


forvalues i=1/50 {
forvalues j=1/50 {
forvalues k=1/50 {
tab record_number if score_pain_`i' <= 3 & score_pain_`j' <= 3 & score_pain_`i+1' <= 3 & ((time_surgerytopainscore`j' - time_surgerytopainscore`i') >= 91.3125) & ((time_surgerytopainscore`j' - time_surgerytopainscore`i') > (time_surgerytopainscore`j' - time_surgerytopainscore`k'))
}
}
}

I would be very thankful for any hints how to get the exclusion of patients reporting scores > 3 in between the visits i and j.
Thank you!