SAS Data Integration Studio, DataFlux Data Management Studio, SAS/ACCESS, SAS Data Loader for Hadoop and others

selecting the last observations of a table by groups

Accepted Solution Solved
Reply
Super Contributor
Posts: 413
Accepted Solution

selecting the last observations of a table by groups

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


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

 

View solution in original post


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,256

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: 10,497

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.

Need further help from the community? Please ask a new question.

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