BookmarkSubscribeRSS Feed
SASdevAnneMarie
Barite | Level 11

Hello Experts,

 

I'm wondering how to translate this code in proc sql : is it possible to write "first" function on proc sql ? 

data table2;
	set table1;
	by prod lb_lg;
	retain N;

	if first.prod then
		do;
			N = 1;
			output;
		end;
	else
		do;
			N = N + 1;
			output;
		end;
run

 Thank you for your help !

4 REPLIES 4
Ksharp
Super User
ods select none;
ods output sql_results=sql;
proc sql number;
select * from sashelp.class order by sex,age;
quit;
ods select all;

proc sql;
create table want as
select *,row-min(row)+1 as n from sql
 group by sex,age
  order by row;
quit;
Kurt_Bremser
Super User

Basically no, because SQL thinks in sets (order irrelevant) and not in a sequence of rows.

As already shown, you can do some tricks, but the data step will outperform them by orders of magnitude.

And you can simplify your data step code, which also improves readability/maintainability:

data table2;
set table1;
by prod lb_lg;
if first.prod
then N = 1;
else N + 1;
run

The SUM statement implies an automatic retain, and since you had OUTPUT in both branches of the IF, you can use the implicit output of the data step.

Sajid01
Meteorite | Level 14

Hello @SASdevAnneMarie 
This can be done indirectly if the idea is to use Proc Sql. I am showing an example with sashelp.class as follows.

proc sql;

create table test as
select *
  from
(select monotonic() as N,* from sashelp.class)
quit;

The first few rows of the output will be as follows

Sajid01_0-1649170646799.png

 

 

 

Kurt_Bremser
Super User

@SASdevAnneMarie but one must always be advised that the working of the (undocumented!) function MONOTONIC is not guaranteed. Depending on the data source, it may not create the expected result.

SAS Innovate 2025: Call for Content

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!

Submit your idea!

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 4 replies
  • 685 views
  • 0 likes
  • 4 in conversation