Your plan needs a little correction first. It's not possible to have two variables called NAME in the same data set. And the values for SEX for bb look like they should be 0 1 0, not 1 0 1.
At any rate, if both data sets contain the same number of observations for aa and bb, you could use:
data z k;
set p;
set L;
if name='aa' then output z;
else output k;
run;
Variations in the code might depend on how many NAME values exist, but this program at least works for the data you provided.
... View more