BookmarkSubscribeRSS Feed
vietlinh12hoa
Obsidian | Level 7

I have the input

IDClass
0A
0A
0B
1A
1C
1C
2B
2B
2C

 

What I want is to extract distinct class values in each ID group by, the output will be something like this:

IDClass AClass BClass C
0210
1102
2021

 

My thought is to use count distinct inside group by something like:

      select ID,
                sum(if(Class='A', 1, 0) as Class_A,
                sum(if(Class='B', 1,0) as Class_B,
                sum(if(Class='C', 1, 0) as Class_C
      from table
      group by ID

But then the problem is that it's inefficiency if we have 100 classes. Any idea we can auto-extract count of distinct classes in group by?

1 REPLY 1
sbxkoenk
SAS Super FREQ

Here you are:

data have;
input ID Class $;
cards;
0	A
0	A
0	B
1	A
1	C
1	C
2	B
2	B
2	C
;
run;
proc freq data=have;
 tables ID * Class / sparse out=count_ID_CLASS(drop=PERCENT);
run;
proc transpose data=count_ID_CLASS out=want;
 by id;
 id class;
run;
/* end of program */

Koen

SAS Innovate 2025: Call for Content

Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!

Submit your idea!

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 1 reply
  • 400 views
  • 0 likes
  • 2 in conversation