Dear all,
I have a dataset in a long format with the same individual having multiple start dates for a script. I need to create a sequence variable so that every time the same individual satisfy a certain criteria, a new sequence should be started for the same individual (variable opioid_scripts_sequence). For example, for patient 13 it started a new medication on one date and was ended on a subsequent visit, so the sequence 1 and 2 are correct. Then, the patient had two visits with no subsequent encounters to continue the medication, and they are considered as missing as they will not be considered for analysis. But finally, there were more four encounter after a certain date that should be considered again as a new sequence (1, 2, 3, 4), instead of the 3, 4, 5, 6 as currently in the last variable.
I have followed different codes, but was unable to create that variable.
Additionally, for each new sequence on the same patient, I need to create a new one containing the number of events in that sequence (e.g. for patient 13 it should be 2 for the first sequence and four for the last sequence).

Please, can someone help me with a code to solve this?

Kind regards
David

Code:
* Example generated by -dataex-. To install: ssc install dataex
clear
input long(patient_number script_date) float(start_date_opioid end_opioid_episode) int sequency_opioid float opioid_start int opioid_scripts_sequence
 1 20025 20025     .  1 0  1
 1 20207     . 20235  2 1  2
 1 20639 20639 20667  3 0  .
 3 21176 21176 21204  1 0  .
10 16153 16153 16181  1 0  .
10 19425 19425     .  2 0  1
10 19439     .     .  3 1  2
10 19445     .     .  4 1  3
10 19471     .     .  5 1  4
10 19535     .     .  6 1  5
10 19541     .     .  7 1  6
10 19548     .     .  8 1  7
10 19589     .     .  9 1  8
10 19611     .     . 10 1  9
10 19662     .     . 11 1 10
10 19692     .     . 12 1 11
10 19710     .     . 13 1 12
10 19828     .     . 14 1 13
10 19898     .     . 15 1 14
10 19971     . 19999 16 1 15
10 20255 20255 20283 17 0  .
10 20956 20956 20984 18 0  .
13 19274 19274     .  1 0  1
13 19387     . 19415  2 1  2
13 19871 19871 19899  3 0  .
13 20751 20751 20779  4 0  .
13 20970 20970     .  5 0  3
13 21067     .     .  6 1  4
13 21159     .     .  7 1  5
13 21301     . 21329  8 1  6
end
format %tdD_m_Y script_date
format %tdD_m_Y start_date_opioid
format %tdD_m_Y end_opioid_episode