简体   繁体   中英

SAS how to Dense_rank

I am new to sas, I used to do oracle SQL

I did similar question before

How to tricky rank SAS?

I thought this question could solve the problem.

but

I got stuck.

so my code is this

data stepstep;
   input emplid KEY:$3. count;
   cards;
11 11Y    1
11 11Y    2
11 11N    3
11 11N    4
11 11Y    5
11 11N    6
12 12Y    1
12 12Y    2
12 12N    3
;
run;

and then I tried

data stepstep2;
   set stepstep;
   by key  emplid NOTSORTED;
   if first.key AND first.emplidthen rank=1;
     ELSE rank+1;
   run;

Output is this

在此处输入图片说明

I want to show

emplid  key   count  rank
11      11Y    1      1
11      11Y    2      1
11      11N    3      2 
11      11N    4      2
11      11Y    5      3
11      11N    6      4
12      12Y    1      1
12      12Y    2      1
12      12N    3      2

so new emplid comes, I want "Rank" goes back to start count from 1.

so this example, when first emplid "12" comes, rank goes back to 1

How can I do that?

You need to leverage your BY groups properly and I think you have them in the wrong order for starters. Try this instead:

    data stepstep2;
       set stepstep;
       by emplid KEY NOTSORTED;

       if first.emplid then rank=1; *start of each emplid group;
       ELSE if first.key rank+1; *start of each new key;

    run;

You can also use a sum statement:

data stepstep2;
  set stepstep;
  by emplid key NOTSORTED;
  if first.emplid then rank=0;
  rank + first.key;
run;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM