BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
whymath
Lapis Lazuli | Level 10
I am doing something needs more than once query in proc sql so I try to write code perform like nest function in data step. Here is an example: Data test have 2 variables, Group and Num.
data test;
  input Group$ Num;
  cards;
  A 10
  A 30
  B 10
  B 40
  C 30
  C 30
  ;
run;

Now I am looking for which Group has the biggest mean value. So firstly I compute mean for each Group, secondly get the max value of these means, Finnaly select the Group whose mean has the same value of the result in step 2.

proc sql;
  select Group, avg(Num) as Mean
  from test
  group by Group
  having Mean = (
    select max(mean) from (
      select avg(Num) as mean from test group by Group
    ) 
  )
  ;
quit;

Yes, I get the right answer, it's "C". But I don't like this method, it is too lengthy. The following code is wrong in syntax:

proc sql;
  select Group, avg(Num) as Mean
  from test
  group by Group
  having Mean = max(avg(Num))
  ;
quit;

But it is much beautiful, and shorter, too. Do you have any better way to do this?

1 ACCEPTED SOLUTION

Accepted Solutions
ed_sas_member
Meteorite | Level 14

Hi @whymath 

Try this:

proc sql;
	select *
	from (select Group, avg(Num) as Mean
		  from test
		  group by Group)
	having Mean = max(Mean);
quit;

Best,

View solution in original post

1 REPLY 1
ed_sas_member
Meteorite | Level 14

Hi @whymath 

Try this:

proc sql;
	select *
	from (select Group, avg(Num) as Mean
		  from test
		  group by Group)
	having Mean = max(Mean);
quit;

Best,

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!

Register Now

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 1 reply
  • 858 views
  • 2 likes
  • 2 in conversation