BookmarkSubscribeRSS Feed
rohitkrishna
Calcite | Level 5

hi all,

I got stuck at one point of my sas code it all about  to retrieve only first and last record of my dataset 

I tried in multiple ways in sas and SQL I succeed in SQL by using max and min statements in the code but till  now I didn't get in sas

so kindly guide the current code for fetch only 2 records that are first and last record 

 

in sas i tried if _n_ = 1;

but i got only first rec i want the last one too

 

 

 

Thnaks & regards 

rohitkrishna

6 REPLIES 6
rohitkrishna
Calcite | Level 5
Hi KurtBremser,
thanks for the quick replay and the code works successfully and I have a query on code
could you plz explain the statement has below mention
{set have point=nobs nobs=nobs;}
Thanks & regards
rohitkrishna
Kurt_Bremser
Super User

nobs=nobs creates a variable (which will not be included in the output) that holds the total number of observations in the dataset. point=nobs uses this variable to retrieve only this last observation.

Since the first statement creates the necessary end-of-file condition to end the data step, no explicit stop statement is needed.

rohitkrishna
Calcite | Level 5
Hi KurtBremser,
thanks for the explanation it's to valuable information

Thanks & regards
rohitkrishna
Tom
Super User Tom
Super User

Just to cover the boundary condition that there is one and only one observation in the source dataset add and IF .

Otherwise the result will have the same observation twice.

data want;
  set have (obs=1);
  output;
  if nobs>1;
  set have point=nobs nobs=nobs;
  output;
run;
Tom
Super User Tom
Super User

Also if you cannot use the NOBS= and/or the POINT= option (perhaps your input is a VIEW instead of dataset) then here is method that will read the whole file and just keep the first and last observation.

data test;
 set sashelp.class end=eof;
 if _n_=1 or eof;
run;

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

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
  • 6 replies
  • 1417 views
  • 4 likes
  • 3 in conversation