BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
ari2495
Obsidian | Level 7

data Db_1;
set Db;
by variable_order;
if first.variable=1 then amount=0;
amount+balance;
if last.variable=1 then output;
run;

Hi, on the code as above i can't understand the use of first and last. Are they simply libraries or have they a specific function?

1 ACCEPTED SOLUTION

Accepted Solutions
Kurt_Bremser
Super User

The FIRST. and LAST. are automatic variables, created for every variable used in the BY statement. They indicate a change in the values of a variable. See this:

data have;
input x;
datalines;
1
1
1
2
2
3
;

data want;
set have;
by x;
f = first.x;
l = last.x;
run;

BTW, your data step will not work, as you use FIRST. and LAST. for a variable not included in the BY.

 

Also note that, for BY to work, the dataset must be sorted by the variable(s), unless the NOTSORTED option is used.

View solution in original post

1 REPLY 1
Kurt_Bremser
Super User

The FIRST. and LAST. are automatic variables, created for every variable used in the BY statement. They indicate a change in the values of a variable. See this:

data have;
input x;
datalines;
1
1
1
2
2
3
;

data want;
set have;
by x;
f = first.x;
l = last.x;
run;

BTW, your data step will not work, as you use FIRST. and LAST. for a variable not included in the BY.

 

Also note that, for BY to work, the dataset must be sorted by the variable(s), unless the NOTSORTED option is used.

hackathon24-white-horiz.png

The 2025 SAS Hackathon Kicks Off on June 11!

Watch the live Hackathon Kickoff to get all the essential information about the SAS Hackathon—including how to join, how to participate, and expert tips for success.

YouTube LinkedIn

Mastering the WHERE Clause in PROC SQL

SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 1 reply
  • 665 views
  • 1 like
  • 2 in conversation