/*录入数据*/
data x1;
input personid 3.0 year_month $10.;
cards;
1 199001
1 199002
1 199005
1 199007
1 199008
1 199210
1 199212
1 199301
1 199302
2 199003
2 199004
2 199006
2 199202
2 199204
;
run;
/*排序*/
proc sort data =x1;
by personid year_month;
run;
/*计算月差month_diff*/
data x2;
set x1;
year_month1=lag(year_month);
month_diff=(substr(year_month,1,4)-substr(year_month1,1,4))*12+substr(year_month,5,2)-substr(year_month1,5,2);
run;
/*retain语句 定义变量seq,1、首次出现personid时,seq=1;
2、非首次出现personid并且月差≥3时,seq自动增加1*/
data x3;
set x2;
retain seq ;
by personid;
if first.personid then seq=1;
if not first.personid and month_diff>=3 then seq=seq+1;
DROP year_month1 month_diff;
run;