proc sort data=aaa out=aaa1;
by id visit;
run;
data wanted;
set aaa1;
by id visit;
lagx=lag(x);
if first.id then call missing(lagx);
if lagx ne . then mean=mean(x,lagx);
if first.id then y=0;
y+mean;
if last.id;
keep id y;
run;