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.

sas-innovate-2026-white.png



April 27 – 30 | Gaylord Texan | Grapevine, Texas

Registration is open

Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!

Register now

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
  • 816 views
  • 1 like
  • 2 in conversation