/*IF vs Where in Datastep using Aggregate Functions*/
data if;
set sashelp.class;
if Max(Age) then output;
run;
data wh;
set sashelp.class;
where Max(Age);
run;
Here I got same output ,I want max age in class dataset
Maxim 1: Read the Documentation, here of the MAX Function:
specifies a numeric constant, variable, or expression. At least one argument is required. If you use only one argument, then the value of that argument is returned.
(emphasis by me)
So in both your examples, the value of age is returned; since all observations in SASHELP.CLASS have a non-missing and non-zero age, the condition will always be true, so all observations are written to the output dataset.
If you want to retrieve the maximum of all ages in SASHELP.CLASS, you need to use the SQL summary function MAX:
proc sql;
select max(age) from sashelp.class;
quit;
The Data Step Max Function reads a list of arguments and returns the largest one. So if you have 1 argument, that argument is returnes. Ie Max(age) = Age.
What is your goal here? Do you really want a single observation in a new data set with the max value for age? Or do you just want to know what max(age) is?
If you want do get it with data step you can do it with help of DoW-loop:
data want1;
do until(eof);
set sashelp.class end=eof;
max = max(max,Age);
end;
do until(end);
set sashelp.class end=end;
if max = Age then output;
end;
run;
But I would use SQL for this task:
proc sql;
create table want2 as
select *
from sashelp.class
having age = max(age)
;
quit;
All the best
Bart
Hi Anandkvn,
Function max() works within single observation.
If you want get max of a variable across the observations you may use methods suggested by KurtBremse and yabwon .
Another way of getting max(AGE) is this:
proc sort data=sashelp.class out=work.class;
by descending AGE;
run;
data work.maxage;
set work.class (obs=1);
put 'max(AGE)=' AGE;
run;
Hope this helps.
Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!
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.
Ready to level-up your skills? Choose your own adventure.