BookmarkSubscribeRSS Feed
deleted_user
Not applicable
I have the case where in a particular table I have customers who might have more than one record (eg Orders). I am wanting to do a query/data step on this table so that I can retrieve only the three most recent records. The table has a timestamp (datetime format) variable that will allow me to sort by date, however I don't know how to limit it to only 3 records per customer.

Any help would be greatly appreciated.

DW
1 REPLY 1
Olivier
Pyrite | Level 9
I'm afraid this can't be done without opening a Code window and typing programming statements.
For example :

PROC SORT DATA = yourDataSet OUT = work.sortedData ;
BY customerId
DESCENDING dateVariable ;
RUN ;
DATA yourFinalDataSet ;
SET work.sortedData ;
BY customerId ;
IF FIRST.customerId THEN nRows = 0 ; /* for a new customer, set nRows to 0 */
nRows + 1 ; /* increment nRows for each observation */
IF nRows <= 3 THEN OUTPUT ;
/* only keep records when nRows < 4 */
RUN ;

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

Creating Custom Steps in SAS Studio

Check out this tutorial series to learn how to build your own steps in SAS Studio.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 1 reply
  • 790 views
  • 0 likes
  • 2 in conversation