## selecting the last observations of a table by groups

Solved
Super Contributor
Posts: 459

# selecting the last observations of a table by groups

hi,

suppose I have the following data&colon;

 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!!

Accepted Solutions
Solution
‎01-15-2016 07:07 PM
Super Contributor
Posts: 490

## Re: selecting the last observations of a table by groups

[ Edited ]
``````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;;``````

All Replies
Solution
‎01-15-2016 07:07 PM
Super Contributor
Posts: 490

## Re: selecting the last observations of a table by groups

[ Edited ]
``````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;;``````

Super User
Posts: 5,853

## Re: selecting the last observations of a table by groups

@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
Super User
Posts: 13,358

## Re: selecting the last observations of a table by groups

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;

🔒 This topic is solved and locked.