Thank you. Here is my solution, there are probably other ways to do this, I wouldn't be surprised if someone else comes up with a shorter solution.
/* Create first flag */
data db2;
set db1;
flag1 = (intnx('month',referencedate,2,'s') <= date <= intnx('month',referencedate,4,'s'));
run;
/* Find IDs with more than one flag */
proc summary data=db2 nway;
class id;
var flag1;
output out=_nflags_ sum=nflags;
run;
/* If more than one flag, determine distance to refdate+3 months */
data db3;
merge db2 _nflags_(drop=_:);
by id;
if nflags>=2 then dist_betw_refdate_plus3months=abs(date-intnx('month',referencedate,3,'s'));
run;
/* Find minimum distance to refdate+3 months and select that one */
proc sort data=db3;
by id dist_betw_refdate_plus3months;
run;
data want;
set db3;
by id dist_betw_refdate_plus3months;
if (flag1=1 and nflags=1) or (flag1=1 and nflags>=2 and first.id);
run;
PS: In the future, don't create date values as character. Create them as numeric and save yourself and all of us here a step.
... View more