data a;
set a;
_date=input(put(date,6.),yymmn6.);
format _date yymmn6.;
rename _date=date;
drop date;
run;
data b;
set b;
_date=input(put(date,6.),yymmn6.);
format _date yymmn6.;
rename _date=date;
drop date;
run;
proc sql;
create table want as
select a.id, a.date from a,b
where a.id=b.id and a.date between intnx('month',b.date,-2) and intnx('month',b.date,2)and a.date^=b.date;
quit;
data a;
input id date;
cards;
1 200910
1 200911
1 201001
1 201004
2 201103
2 201105
2 201107
2 201108
;
run;
data B;
input id date;
cards;
1 201001
2 201105
;
run;
data want(rename=(_id=id _date=date));
if 0 then set a(rename=(id=_id date=_date));
declare hash h(dataset:'a(rename=(id=_id date=_date))',multidata:'y',ordered:'y');
h.definekey('_id','_date');
h.definedata(all:'y');
h.definedone();
declare hiter hi('h');
set b;
rc=hi.setcur(key:id,key:date);
hi.prev();
output;
hi.next();
output;
hi.next();
output;
drop id date rc;
run;
手写的代码,没调试过,需楼主自己去调试了:
proc sort data=a;
by id date;
run;
proc sort data=b;
by id date;
run;
data c1 c2;
Merge a b(rename=(date=basedate));
By id;
If date<basedate then output c1;
Else if date>basedate then output c2;
Drop basedate;
Run;
Proc sort data=c1;
By id descending date;
Run;
Data c1;
Set c1;
By id;
If first.id then n=0;
N+1;
If n<=2;
Drop n;
Run;
Proc sort data=c1;
By id date;
Run;
Data c2;
Set c2;
By id;
If first.id then n=0;
N+1;
If n<=2;
Drop n;
Run;
Data c;
Set c1 c2;
By id;
Run;