BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
pavank
Quartz | Level 8
Data b;
input cc swipe;
cards;
1 200
1 300
1 200
1 900
2 1300
2 1400
2 1500
;
run;




proc sort data=b;
by cc;
run;


data last_second;
  set b;
  by cc;
last_second_value = lag(swipe);
if last.cc then do;
    output;
  end;
  drop swipe;
run;
 How to get last second values using PROC SQL Method 
output
cc swipe
1 200
2 1400
1 ACCEPTED SOLUTION

Accepted Solutions
Kurt_Bremser
Super User

SQL does not have a concept of sequence, it works with sets. Stay with the DATA step, e.g.

data last_second;
do until (last.cc);
  set b;
  by cc;
  if not last.cc then last_second_value = swipe;
end;
drop swipe;
run;

Your code can be simplified by using a Subsetting IF:

data last_second;
set b;
by cc;
last_second_value = lag(swipe);
if last.cc and not first.cc;
drop swipe;
run;

The expanded condition takes care of cases where there's only one observation for a cc group.

View solution in original post

1 REPLY 1
Kurt_Bremser
Super User

SQL does not have a concept of sequence, it works with sets. Stay with the DATA step, e.g.

data last_second;
do until (last.cc);
  set b;
  by cc;
  if not last.cc then last_second_value = swipe;
end;
drop swipe;
run;

Your code can be simplified by using a Subsetting IF:

data last_second;
set b;
by cc;
last_second_value = lag(swipe);
if last.cc and not first.cc;
drop swipe;
run;

The expanded condition takes care of cases where there's only one observation for a cc group.

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 16. 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
  • 1 reply
  • 292 views
  • 0 likes
  • 2 in conversation