BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
DiG
Fluorite | Level 6 DiG
Fluorite | Level 6

Hi,

 

A seemingly easy task of summarizing a variable by group has become challenging when I was asked to find the sum of only top three values in each group. I attached a sample table here. Need to find the totals of top 3 amounts for each industry group (amounts are already sorted in descending order). Some industry groups have only one or two records. Can anybody help me with this?

 

Thanks.

1 ACCEPTED SOLUTION

Accepted Solutions
novinosrin
Tourmaline | Level 20

Are you after this?

 


data have;
input memberid : $	industry	amount;
cards;
A2348	110	10045643
A5469	110	9543376
A21563	110	9034166
D6765	110	4876
B2345	110	46
A5463	111	89
A9876	111	30
B8766	112	583497
A5689	112	525488
D9655	112	75158
A4566	112	43866
D67896	112	1865
D4566	112	568
A2876	112	366
;

data want;
if 0 then set have;
sum=0;
do _n_=1 by 1 until(last.industry);
set have;
by industry;
sum+(_n_<=3)*amount;
end;
drop amount;
run;

 

View solution in original post

3 REPLIES 3
novinosrin
Tourmaline | Level 20

Are you after this?

 


data have;
input memberid : $	industry	amount;
cards;
A2348	110	10045643
A5469	110	9543376
A21563	110	9034166
D6765	110	4876
B2345	110	46
A5463	111	89
A9876	111	30
B8766	112	583497
A5689	112	525488
D9655	112	75158
A4566	112	43866
D67896	112	1865
D4566	112	568
A2876	112	366
;

data want;
if 0 then set have;
sum=0;
do _n_=1 by 1 until(last.industry);
set have;
by industry;
sum+(_n_<=3)*amount;
end;
drop amount;
run;

 

DiG
Fluorite | Level 6 DiG
Fluorite | Level 6

It works!

Thank you  !

novinosrin
Tourmaline | Level 20

@DiG  if the previous is not clear. the traditional method as follows

 

data want;
set have;
by industry;
if first.industry then do; n=1;sum=0;end;
else n+1;
sum+(n<=3)*amount;
if last.industry;
drop n amount;
run;

SAS Innovate 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 3 replies
  • 961 views
  • 1 like
  • 2 in conversation