In the TEST data, some hospitals don't have any records in the previous year, I suspect that it might be that way in the full data set as well. Anyway, here is my solution using the TEST data, I leave it up to you to check to see if I have the right means.
/* Find all distinct dates in the data set */
proc sql;
create table dates as select distinct admit_date from test;
quit;
/* Create multi-label format for dates, so we can find average of previous year*/
data dates1;
set dates;
start=intnx('year',admit_date,-1,'s');
end=admit_date-1;
fmtname='datef';
hlo='M';
label=put(start,mmddyys10.);
run;
proc format cntlin=dates1;
run;
/* Compute means over previous year using Multilabel format */
proc summary data=test nway;
class hospital_number;
class admit_date/mlf;
var opioid_sum;
format admit_date datef.;
output out=means mean=opioid_mean;
run;
/* Combine means with original data */
proc sql;
create table final as select
t.*,m.opioid_mean
from test as t left join means as m
on t.hospital_number=m.hospital_number
and t.admit_date=intnx('year',input(m.admit_date,mmddyy10.),1,'s')
order by t.hospital_number,t.admit_date;
quit;
... View more