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: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

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