Hello,
I have a dataset containing an ID variable and the variables named MQ1 to MQ20 and LQ1 to LQ20. Each ID can have more than one value for MQ1 to MQ20 and LQ1 to LQ20.
Now I want to create a new table keeping only the max value for each variable by ID using proc sql. My current code looks like this:
proc sql;
create table want as
select ID, max(MQ1) as MQ1, max(MQ2) as MQ2, max(MQ3) as MQ3, max(MQ4) as MQ4, max(MQ5) as MQ5, max(MQ6) as MQ6, max(MQ7) as MQ7, max(MQ8) as MQ8, max(MQ9) as MQ9, max(MQ10) as MQ10, max(MQ11) as MQ11, max(MQ12) as MQ12, max(MQ13) as MQ13, max(MQ14) as MQ14, max(MQ15) as MQ15, max(MQ16) as MQ16, max(MQ17) as MQ17, max(MQ18) as MQ18, max(MQ19) as MQ19, max(MQ20) as MQ20,
max(LQ1) as LQ1, max(LQ2) as LQ2, max(LQ3) as LQ3, max(LQ4) as LQ4, max(LQ5) as LQ5, max(LQ6) as LQ6, max(LQ7) as LQ7, max(LQ8) as LQ8, max(LQ9) as LQ9, max(LQ10) as LQ10, max(LQ11) as LQ11, max(LQ12) as LQ12, max(LQ13) as LQ13, max(LQ14) as LQ14, max(LQ15) as LQ15, max(LQ16) as LQ16, max(LQ17) as LQ17, max(LQ18) as LQ18, max(LQ19) as LQ19, max(LQ20) as LQ20
from have
group by ID;
quit;
As my code looks like this quite often I wonder whether there is an easy way to shorten this?
Thank you!
The easiest way to shorten the code is to get rid of SQL:
proc summary data=have nway;
class ID;
var MQ1-MQ20 LQ1-LQ20;
output out=want (drop=_type_ _freq_) max=;
run;
The easiest way to shorten the code is to get rid of SQL:
proc summary data=have nway;
class ID;
var MQ1-MQ20 LQ1-LQ20;
output out=want (drop=_type_ _freq_) max=;
run;
proc means data=sashelp.class noprint nway;
class age;
var _numeric_;
output out=want max= / autoname;
run;
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!
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.