Question

I have columns named id and key. I sorted the data by id and I need to get the first 5 keys of every id.

PROC SQL OUTOBS=5;
   CREATE TABLE WORK.QUERY_001 AS 
   SELECT DISTINCT t1.*      
      FROM work.DATA t1
      ORDER BY t1.id,
               t1.key DESC;
QUIT;
Was it helpful?

Solution

The OUTOBS= option on your PROC SQL statement applies to the query as a whole, so with your example you would get only five rows returned.

The following code applies a counter i that resets each time a new id value is encountered. If the i value is five or less (i.e. first five rows for each id) then the row is written to the new dataset:

proc sort data=data;
  by id descending key;
run;

data query_001 (drop=i);
  set data;
    by id descending key;
    if first.id then i=0;
    i+1;
    if i <=5;
run;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top