I think I am still confused,you have too many scenarios to take into account of .
Assuming I understood what you mean.
But I think you'd better post an input dataset to let me test the code ,and output dataset(important) to verify my code's result.
data have;
input customer $ customer_rank promo_id promo_score;
datalines;
carl 1 4000 9
carl 1 4001 7
carl 1 4002 4
carl 1 4003 3
jess 2 4000 9
jess 2 4004 7
jess 2 4002 5
jess 2 4001 3
robb 3 4004 8
robb 3 4000 6
robb 3 4002 5
robb 3 4008 2
amii 4 4004 8
amii 4 4000 7
amii 4 4001 4
amii 4 4002 3
xcarl 11 14000 9
xcarl 11 14001 7
xcarl 11 14002 4
xcarl 11 14003 3
xjess 21 14000 9
xjess 21 14004 7
xjess 21 14002 5
xjess 21 14001 3
xrobb 31 14004 8
xrobb 31 14000 6
xrobb 31 14002 5
xrobb 31 14008 2
xamii 41 14004 8
xamii 41 14000 7
xamii 41 14001 4
xamii 41 14002 3
;
run;
%let n_Promo_ID_each_customer=2;
%let n_Promo_ID_all_customer=10;
proc sort data=have out=temp;
by customer_rank descending promo_score;
run;
data want;
if _n_=1 then do;
if 0 then set temp;
declare hash h();
h.definekey('promo_id');
h.definedone();
end;
set temp;
by customer_rank;
retain count 0;
if first.customer_rank then count=0;
if h.num_items<&n_Promo_ID_all_customer. then do;
if h.check() ne 0 and count<&n_Promo_ID_each_customer. then do;h.add();count+1;output;end;
end;
drop count;
run;
... View more