BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
aalluru
Obsidian | Level 7

I'm joining table a with table b using a left join and I want the resultant table to be in the same order that table a was in. However the order seems to be changing to the ascending order of the variable that I used to join on. How can I prevent that from happening?

1 ACCEPTED SOLUTION

Accepted Solutions
FreelanceReinh
Jade | Level 19

Hi @aalluru,

 

In this case create your own (temporary) sort key and use that in the ORDER BY clause.

 

Example:

/* Create sample data for demonstration */

data have_a;
set sashelp.classfit;
keep name predict;
run;

data have_b;
set sashelp.class;
keep name age;
run;

/* Create view with a sort key (sequential number) */

data _have_a / view=_have_a;
set have_a;
_seqno=_n_;
run;

/* Perform left join maintaining sort order of HAVE_A and delete the view */

proc sql;
create table want(drop=_seqno) as
select a.*, age
from _have_a a left join have_b b
on a.name=b.name
order by _seqno;

drop view _have_a;
quit;

 

View solution in original post

4 REPLIES 4
maguiremq
SAS Super FREQ

Do you know what the table on the left was ordered by originally? You can use an `ORDER BY` clause after your join if it's that simple.

 

You'd probably need to specify the variable that it was sorted on along with its alias (e.g., ORDER BY a.unique_id).

aalluru
Obsidian | Level 7

The table on the left was in a random order

FreelanceReinh
Jade | Level 19

Hi @aalluru,

 

In this case create your own (temporary) sort key and use that in the ORDER BY clause.

 

Example:

/* Create sample data for demonstration */

data have_a;
set sashelp.classfit;
keep name predict;
run;

data have_b;
set sashelp.class;
keep name age;
run;

/* Create view with a sort key (sequential number) */

data _have_a / view=_have_a;
set have_a;
_seqno=_n_;
run;

/* Perform left join maintaining sort order of HAVE_A and delete the view */

proc sql;
create table want(drop=_seqno) as
select a.*, age
from _have_a a left join have_b b
on a.name=b.name
order by _seqno;

drop view _have_a;
quit;

 

aalluru
Obsidian | Level 7
Yes! This worked! Thank you!!

Ready to join fellow brilliant minds for the SAS Hackathon?

Build your skills. Make connections. Enjoy creative freedom. Maybe change the world. Registration is now open through August 30th. Visit the SAS Hackathon homepage.

Register today!
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.

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
  • 4 replies
  • 3111 views
  • 1 like
  • 3 in conversation