Solved
Contributor
Posts: 43

# Monotonic function with group by proc sql

Hello,

I would like to create a monotonic() function that would go from 1 to n based on another variable such that if i have a dataset with years, it goes from 1 to x for 2012, 1 to y for 2013, 1 to z for 2014 and so on... is there a way to acheive that? I tried the "group" by function but no luck!

Thanks!

``````proc sql;
create table want as select
year,
name,
score,
monotonic() as row
from have;
quit; ``````

Accepted Solutions
Solution
‎06-28-2017 08:48 AM
Super User
Posts: 9,840

## Re: Monotonic function with group by proc sql

Please follow the guidance next to Post button when you start a new question.  Post example test data in the form of a datastep, and show what you want out.  Explain any logic between the two, this avoids us guessing what you want to do.  As @kiranv_ has shown datastep would be simpler for this task, a minor update to use the binary functions:

```data want;
set have;  by year;
n=ifn(first.year,1,sum(n,1));
run;```

I note all of your questions are about SQL, is there a reason you avoid using Base SAS?  You will find that both have their benefits - SQL for instance does not care about sort on its data as it does it internally, datastep is good at linear steps through data such as this problem.  Unless you connect to a database there really is no need to limit yourself to one or the other.

All Replies
PROC Star
Posts: 549

## Re: Monotonic function with group by proc sql

[ Edited ]

Something like this by datastep. if you can show a sample of have and want that would make it easier.

```data have;
input year name \$;
datalines;
2014 sam
2014 ram
2014 kam
2013 nam
2013 bam
2013 lam
;
run;

proc sort data =have;
by year name;
run;

data want;
set have;
by year;
if first.year then sum=1;
else sum+1;
run; ```

Solution
‎06-28-2017 08:48 AM
Super User
Posts: 9,840

## Re: Monotonic function with group by proc sql

Please follow the guidance next to Post button when you start a new question.  Post example test data in the form of a datastep, and show what you want out.  Explain any logic between the two, this avoids us guessing what you want to do.  As @kiranv_ has shown datastep would be simpler for this task, a minor update to use the binary functions:

```data want;
set have;  by year;
n=ifn(first.year,1,sum(n,1));
run;```

I note all of your questions are about SQL, is there a reason you avoid using Base SAS?  You will find that both have their benefits - SQL for instance does not care about sort on its data as it does it internally, datastep is good at linear steps through data such as this problem.  Unless you connect to a database there really is no need to limit yourself to one or the other.

Contributor
Posts: 43

## Re: Monotonic function with group by proc sql

Thank you! I'll note that for the future. I am more familiar with SQL and the data I use is most often from data warehouse-type sources.
☑ This topic is solved.