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

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
  • 653 views
  • 0 likes
  • 2 in conversation