Solved
Contributor
Posts: 27

# Select max value in proc sql

Hi all,

at the moment, I've got a code which does the following:

1) sorts a DATASET1 by a VAR1 in ascending order, then by VAR2 in ascending order

2) selects removes duplicates of VAR1, but selects the highest value of VAR2

3) appends this to DATASET2 to another one by VAR1

Is it possible to combine these three steps into 1 using a proc sql?

so like

proc sql;

create table NEWTABLE as select

a.*, b.VAR2

from DATASET1 as a

left join DATASET2( [conditions which make 1-3 work]) as b on b.VAR1 = a.VAR1;

quit;

thanks,

Marco

Accepted Solutions
Solution
‎04-01-2014 06:20 AM
Super User
Posts: 9,599

## Re: Select max value in proc sql

So condition 1 and 2 are fulfilled by the subquery (select VAR1,MAX(VAR2) from DATASET1 group by VAR1).  This should return one VAR1 with the maximum VAR2 within that group.  Then the other dataset is left joined onto that.

All Replies
Super User
Posts: 9,599

## Re: Select max value in proc sql

Hi,

Could you clarify your request a bit.  A left join is not an append but a merge.  You have also put conditions 1-3 in the from of dataset 2 where 1 and 2 are applicable to only dataset 1 from your text.  As a rough guess:

proc sql;

create table WANT as

select     A.*,

B.VAR3

from       (select VAR1,MAX(VAR2) from DATASET1 group by VAR1) A

left join   DATASET2 B

on           A.VAR1=B.VAR1;

quit;

Contributor
Posts: 27

## Re: Select max value in proc sql

You're right, I got the datasets mixed up.

This is what I would have wanted:

proc sql;

create table NEWTABLE as select

a.*, b.VAR2

from DATASET2 as a

left join DATASET1( [conditions which make 1-3 work]) as b on b.VAR1 = a.VAR1;

quit;

thanks,

Marco

Solution
‎04-01-2014 06:20 AM
Super User
Posts: 9,599