Finding MIN (or even MAX) of character variables in SQL
It is perfectly valid to use min() as a summary function on character values in proc sql, eg as follows:
proc sql;
create table test as
select min(name) as minval
from sashelp.class;
This is not so, however, when using in an inline context:
proc sql;
create table test as
select min(name,sex) as minval
from sashelp.class;
Which gives:
ERROR: Function MIN requires a numeric expression as argument 1.ERROR: Function MIN requires a numeric expression as argument 2.
So what are the alternatives? If we were in datastep, we might have had the option of the little-known infix operator for min (><):
data null;minval=‘Less’><‘More’><‘Lots’;put minval=; /_ minval=Less /run;
As it happens though, the min & max infix operators are not valid in proc sql. Another approach, if comparing just two values, would be ifc() - eg:
proc sql;
create table test as
select ifc(name<sex,name,sex) as minval
from sashelp.class;
But what if we have more than two values? In this instance, it becomes necessary to take matters into your own hands! I’ve gone ahead and rolled up an FCMP function below, which could surely be improved, but does the job when comparing three character values in either data step or proc sql:
proc fcmp outlib=work.myfuncs.test;
function minC(a $, b $, c $) $;
length result $1000;
result=a><b><c;
return (result);
endsub;
quit;
options cmplib=work.myfuncs;
data null_;
x=‘Killing’;
y=‘Me’;
z=‘Softly’;
outvar=minC(x,y,z);
put outvar=;
run;
proc sql;
create table test as
select minC(‘Constant’,name,sex)
from sashelp.class;