/***************************************************************************************************************** SAS file name: top_n.sas File location: __________________________________________________________________________________________________________________ Purpose: To demonstrate how to find top n by groups in SAS Author: Peter Clemmensen Creation Date: 13/04/2020 This program supports the blog post "3 Ways to Select Top N By Group in SAS" on SASnrd.com *****************************************************************************************************************/ /* Proc Rank */ proc rank data=sashelp.iris out=rank descending ties=low; by species; var SepalLength; ranks r; run; proc sort data=rank; where r <= 3; by species r; run; /* Proc Summary */ proc summary data=sashelp.iris nway noprint; class species; var SepalLength; output out=temp(drop=_:) idgroup ( max(SepalLength) out[3] (SepalLength)=) /autolabel autoname; run; proc transpose data=temp out=want(drop=_: rename=col1=SepalLength); by Species; run; /* Hash Object */ data want; if _N_ = 1 then do; declare hash h (dataset : 'sashelp.iris(obs=0)', ordered : 'd', multidata : 'Y'); h.definekey ('SepalLength'); h.definedata (all : 'y'); h.definedone(); declare hiter hi ('h'); end; do until (last.Species); set sashelp.iris; by Species; h.ref(); end; do _N_ = 1 by 1 while (hi.next() = 0 & _N_ <= 3); output; end; _N_ = hi.first(); _N_ = hi.prev(); h.clear(); run;