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 ;

sas-innovate-2026-white.png



April 27 – 30 | Gaylord Texan | Grapevine, Texas

Registration is open

Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!

Register now

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
  • 837 views
  • 0 likes
  • 2 in conversation