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!!
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;;
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;;
@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?
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;
Join us for SAS Innovate 2025, our biggest and most exciting global event of the year, in Orlando, FL, from May 6-9. Sign up by March 14 for just $795.
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.