BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
cosmid
Lapis Lazuli | Level 10

Hi,

 

data a;
  input ID x;
datalines;
1 a
1 b
3 c
run;

data b;
  input ID y;
datalines;
1 a
1 b
1 c
run;

data c;
  merge a b;
  by ID;
run;

The result is:

obs ID x y
  1  1 a a
  2  1 b b
  3  1 b c
  4  3 c

My question is, is there a way to produce an output as follows:

obs ID x y
  1  1 a a
  2  1 b b
  3  1   c
  4  3 c

Thanks

1 ACCEPTED SOLUTION

Accepted Solutions
Tom
Super User Tom
Super User

The reason a one to many merge works in the SAS data step is because variables coming from input datasets are RETAINED.   To prevent that you just need to add your own code to clear them.  That is very easy to do using CALL MISSING().  Just make sure to write the observation BEFORE you clear the values.

data c;
  merge a b;
  by ID;
  output;
  call missing(of _all_);
run;

View solution in original post

2 REPLIES 2
Tom
Super User Tom
Super User

The reason a one to many merge works in the SAS data step is because variables coming from input datasets are RETAINED.   To prevent that you just need to add your own code to clear them.  That is very easy to do using CALL MISSING().  Just make sure to write the observation BEFORE you clear the values.

data c;
  merge a b;
  by ID;
  output;
  call missing(of _all_);
run;
Patrick
Opal | Level 21

I normally prefer SQL for such cases. I feel it's "cleaner".

data a;
  input ID x $;
datalines;
1 a
1 b
3 c
;
run;

data b;
  input ID y $;
datalines;
1 a
1 b
1 c
;
run;

proc sql;
/*   create table want as */
  select 
    coalesce(a.id,b.id) as id,
    a.x,
    b.y
  from a
  full join b 
  on a.id=b.id and a.x=b.y
  ;
quit;

 

Patrick_0-1740019663485.png

The relationship between your tables with the keys used is actually not many:many but 1:1 (well: 1 or zero : 1 or zero).
For many:many joins the result (number of rows) between a SQL join and a data step merge will differ (most of the time you're after the SQL result).

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

Mastering the WHERE Clause in PROC SQL

SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 2 replies
  • 1010 views
  • 5 likes
  • 3 in conversation