Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SAS PROC SQL to join two tables using FULL JOIN

Tags:

sas

Suppose I have two datasets,

--Table 1--      --Table 2--
ID  Amount       ID  Amount1 Code
A01   0.1        A01  0.3     x
A02   0.2        A02  0.2     y
A02   0.3        A03  0.4     g 
A03   0.4        A03  0.5     u
A05   0.6        B01  0.1     k

I am trying to create a new dataset (Table 3) by joining Table 1 and Table 2. The intended final result should look like this:

--Table 3--
ID  Amount  Amount1  Code
A01   0.1     .       .
A01   .       0.3     x
A02   0.2     0.2     y
A02   0.3     .       .
A03   0.4     0.4     g
A05   0.6     .       .
B01   .       0.1     k

where the table will be joined based on the ID with the amount and amount1 compared at the same time. I tried using PROC SQL FULL JOIN but the results appear to be a little weird. Thank you.

like image 500
saspower Avatar asked Mar 18 '23 13:03

saspower


1 Answers

The only thing that may not be obvious for a novice user is necessity to do coalesce() on IDs.

proc sql;
create table joined as
select coalesce(a.ID, b.ID) as ID, a.Amount, b.Amount1, b.Code
from Table1 a
full join Table2 b
on a.ID = b.ID;
quit;

Anyway, SAS way to do this is merge of the two tables. If you have the tables pre-sorted or have index on IDs, this would be also more efficient:

data merged;
merge table1 table2;
by ID;
run;
like image 104
vasja Avatar answered Apr 29 '23 20:04

vasja