BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
Fluorite | Level 6

## Using Rank to find the top nn values (1 in this case)

I have been unsuccessfully struggling with Rank to do what I think should be a simple task.

Essentially, I want to group a table (with many columns) by the first 2 columns and select all records where the group number for the second column=1.

Picture an auto service center database for a simplified example of what I'm trying to do:

The first few columns are : Customer ID / Date of Service / Service Code / etc.

So I want all data for each customer regarding their most recent date of service.

The roadblock for me is that Rank produces the observation number instead of the position in the group, or subgroup, leaving me no way to select the most recent date of service.

In practice, even if I set the 'LOW' option for ties, I can't check for Date-Of-Service-Rank = 1 because it's the low observation number, not the position in the group. So, if there were 99 records for the first customer, then for the second customer all of the records I want might have Date-Of-Service-Rank=100.

Am I going about this the wrong way?  I hope my example makes sense.

1 ACCEPTED SOLUTION

Accepted Solutions
Opal | Level 21

## Re: Using Rank to find the top nn values (1 in this case)

Proc rank creates ranks for individual observations, not for groups or clusters of observations. If your data is sorted, you could get those ranks simply with:

``````data want;
set have; by customerId dateOfService;
if first.customerId then rank=0;
if first.dateOfService then rank+1;
run;``````
PG
3 REPLIES 3
Super User

## Re: Using Rank to find the top nn values (1 in this case)

Show what you tried please and we can tell you where you're going wrong.
Opal | Level 21

## Re: Using Rank to find the top nn values (1 in this case)

Proc rank creates ranks for individual observations, not for groups or clusters of observations. If your data is sorted, you could get those ranks simply with:

``````data want;
set have; by customerId dateOfService;
if first.customerId then rank=0;
if first.dateOfService then rank+1;
run;``````
PG
Fluorite | Level 6

## Re: Using Rank to find the top nn values (1 in this case)

Thank you PGStats and Reeza.

From PGStats' explanation, it looks like I was trying to use the Rank procedure for something it wasn't designed for.

Since I am trying to find the first item within each group, I will instead create a temporary table that only contains data from the first sub-group and then process that table instead.

Thank you for your fast responses.  Much appreciated.

Discussion stats
• 3 replies
• 476 views
• 0 likes
• 3 in conversation