BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
ilikesas
Barite | Level 11

hi,

 

suppose I have the following data:

stock

year

price

A

2009

1

A

2009

1.5

A

2010

2

A

2010

3

B

2009

10

B

2009

7

B

2010

4

B

2010

5

 


What I would like to have is a new table that contains the last observation for each stock-year combination:

 

stock

year

price

A

2009

1.5

A

2010

3

B

2009

7

B

2010

5

 

Thank you!!

1 ACCEPTED SOLUTION

Accepted Solutions
mohamed_zaki
Barite | Level 11
data want ;
set have;
by Stock year;
if last.year then output;
run;

That based on the fact that your data are sorted by stock year;

Or you should sort them first 

As

proc sort data=have out=have_sorted;
by stock year;
run;

data want ;
set have_sorted;
by Stock year;
if last.year then output;
run;;

 

View solution in original post

3 REPLIES 3
mohamed_zaki
Barite | Level 11
data want ;
set have;
by Stock year;
if last.year then output;
run;

That based on the fact that your data are sorted by stock year;

Or you should sort them first 

As

proc sort data=have out=have_sorted;
by stock year;
run;

data want ;
set have_sorted;
by Stock year;
if last.year then output;
run;;

 

LinusH
Tourmaline | Level 20

@mohamed_zaki points at the appropriate solution for this.

But I'm a bit concerned about your data set. How do you know that the data is in the correct order? The order is crucial since you wish to chose the last record for your by group.

Perhaps you have additional variables that you don't share, such as a date/timestamp, or a sequence no?

Data never sleeps
ballardw
Super User

If your existing data is ordered correctly but the STOCK is not in a nice sort order you can use the solution from @mohamed_zaki but with
By notsorted stock year;

sas-innovate-2024.png

Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.

Pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.

 

Register now!

How to connect to databases in SAS Viya

Need to connect to databases in SAS Viya? SAS’ David Ghan shows you two methods – via SAS/ACCESS LIBNAME and SAS Data Connector SASLIBS – in this video.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 3 replies
  • 935 views
  • 4 likes
  • 4 in conversation