BookmarkSubscribeRSS Feed
deleted_user
Not applicable
Hi all,
I have a question regarding proc sql sintax.
I need to find top 5 rows in a query which contains group by.
In particolar I need top 5 for each aggegation groups and not 5 rows at all.
In Oracle sintax I think I could use "Partition By" over a given rank in order to apply this wish.
Could you please suggest me a workaround to use in proc sql or a specific function if existing?

I really thank you a lot in advance for your support!

KR

Daniele.
2 REPLIES 2
Doc_Duke
Rhodochrosite | Level 12
I don't know a one-step approach, but I could do it in three.

First SORT by group, then use PROC RANK with a BY on the group to get the ranks, and then either a DATA step or PROC SQL to pull them off.
ChrisNZ
Tourmaline | Level 20
If you only want the top 5, the outobs= option is your friend.

If you have group by, you probably need 2 steps as in:

[pre]

proc sql; * find best selling products by region;
create view SUM as
select REGION, PRODUCT, sum(SALES) as SALES
from SASHELP.SHOES
group by REGION, PRODUCT
order by REGION, SALES desc ;
quit;


data TOP3; * keep the top 3 for each region;
set SUM;
by REGION ;
if first.REGION or lag(first.REGION) or lag2(first.REGION);
run;


data TOP3; * keep the top 3 for each region, alternative method;
set SUM;
by region ;
if first.REGION then N=0;
N+1;
if N <= 3;
drop N;
run;

sas-innovate-2024.png

Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.

Pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.

 

Register now!

What is Bayesian Analysis?

Learn the difference between classical and Bayesian statistical approaches and see a few PROC examples to perform Bayesian analysis in this video.

Find more tutorials on the SAS Users YouTube channel.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 2 replies
  • 12973 views
  • 0 likes
  • 3 in conversation