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).

sas-innovate-2026-white.png



April 27 – 30 | Gaylord Texan | Grapevine, Texas

Registration is open

Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!

Register now

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
  • 1085 views
  • 5 likes
  • 3 in conversation