You can create a date value from its using mdy()
function, like this:
data have;
input Year Month Id Type $;
datalines;
2010 3 1 A
2010 5 2 B
2010 10 1 A
2010 12 1 A
;
run;
data have;
set have;
format date date9.;
date = mdy(Month, 1, Year);
run;
You don't have a day value, so I just used 1 (every date created is the first of the month).
Now, you can join the two tables by ID, and calculate the difference from date in the first table and promotion date in the second table:
proc sql;
create table want as
select *
,abs(date - promote) as diff
from have as a
left join
prom as b
on a.id = b.id;
quit;
After that you sort the resulting table by id, date and diff:
proc sort data=want;
by id date diff;
run;
After sorting dataset looks like this:
Year Month Id Type date Promote diff
---------------------------------------------------
2010 3 1 A 01MAR2010 20FEB2010 9
2010 3 1 A 01MAR2010 20MAY2010 80
2010 5 2 B 01MAY2010 . .
2010 10 1 A 01OCT2010 20MAY2010 134
2010 10 1 A 01OCT2010 20FEB2010 223
2010 12 1 A 01DEC2010 20MAY2010 195
2010 12 1 A 01DEC2010 20FEB2010 284
Last step, iterate through the dataset and check if the first diff
value for every ID and date value is lower, or greater then 3 months (I just checked against 90 days, you could use also intck
function). Because we sorted the dataset by id, date and diff the first row should be the nearest to the date, so you output
only the first row.
data want2(keep = year month id type duration);
set want;
by date;
if first.date and Type = 'A' then do;
if diff lt 90 then do;
duration = 'A < 3 months';
output want2;
end;
if diff gt 90 then do;
duration = 'A > 3 months';
output want2;
end;
end;
else if first.date then do;
duration = type;
output want2;
end;
run;
output
statements are used because we want to keep only some of the rows (first one for each by group). The last output
is there so that the rows with a type value different then A also stay in the final result.
This is the final result:
Year Month Id Type duration
--------------------------------------------
2010 3 1 A A < 3 months
2010 5 2 B B
2010 10 1 A A > 3 months
2010 12 1 A A > 3 months