BookmarkSubscribeRSS Feed
pacman94
Calcite | Level 5

I have the following data

IDDategroup
11/2/20211
11/3/20212
21/2/20212
31/5/20212
41/4/20211
41/5/20212

 

What I would like to do is that

for each ID, I need to take the max group and add additional groups

if ID only has one instance then keep that new_group as is

if the ID has more than one instance then new_group = '2 Indirect'

like this

 

then only keep the new group

IDDategroupnew_group
11/2/20211 
11/3/202122 Indirect
21/2/202122
31/5/202122
41/4/20211 
41/5/202122 Indirect

 

i did the following

proc sql;

select *, max(group) as group

from data;

group by id;

quit; 

1 REPLY 1
Reeza
Super User

Use COUNT DISTINCT to count the number of unique values in a column. 

 

FYI - I'm assuming you want the final code to be GROUP# + DIRECT, ie 3 Direct if 3 was the maximum. Your data doesn't show a 3 but if it was possible this still works. 

 

EDIT: Modified to use calculated key word and only display results for the max group records. 

 

proc sql;
select *, max(group) as max_group,
        case when count(distinct group) > 1 and group = max_group then catt(calculated max_group, " Direct")
        else if group = calculated max_group then calculated max_group 
else " "
end as new_group from data; group by id; quit;

@pacman94 wrote:

I have the following data

ID Date group
1 1/2/2021 1
1 1/3/2021 2
2 1/2/2021 2
3 1/5/2021 2
4 1/4/2021 1
4 1/5/2021 2

 

What I would like to do is that

for each ID, I need to take the max group and add additional groups

if ID only has one instance then keep that new_group as is

if the ID has more than one instance then new_group = '2 Indirect'

like this

 

then only keep the new group

ID Date group new_group
1 1/2/2021 1  
1 1/3/2021 2 2 Indirect
2 1/2/2021 2 2
3 1/5/2021 2 2
4 1/4/2021 1  
4 1/5/2021 2 2 Indirect

 

i did the following

proc sql;

select *, max(group) as group

from data;

group by id;

quit; 


 

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
  • 1 reply
  • 352 views
  • 0 likes
  • 2 in conversation