In the example below I have created OVERLAP_FLAG, which is equal to 1 where two consecutive regimens overlap and their start dates are within 28 days of one another.

My plan is to number each group of flags with a view to merging each overlapping group of regimens together.

As you can see from the example below, this is complicated by the fact that some patients have multiple groups of overlapping regimens.

Is there a straightforward way of numbering each group in a distinct fashion within each patient? For example, so that the first three flags form a group coded to 1 and the second solitary flag becomes 2, etc. This would be easy if were was a variable on which to sort the flags.

Code:
* Example generated by -dataex-. To install: ssc install dataex
clear
input long id double regimen float(start_date end_date regimen_overlap overlap_flag)
9942  222346 20577 20587   . .
9942  222347 20577 20605   0 1
9942 1194964 20591 20643   0 1
9942 1194965 20591 20628  14 1
9942  222349 20741 20752 150 .
9942  222348 20763 20842  22 .
9942  222350 20766 20850   3 1
end
format %td start_date_of_regimen
format %td end_date_of_regimen