BookmarkSubscribeRSS Feed
pacman94
Calcite | Level 5

I have 2 datasets - one demo (1 row per ID) and one specific event (multiple row per ID). What I would like to do is merge these two tables but have yes_no from the specific event table for one that matches. If there are two or more event in specific table, it should show 1 and 0 for the Ids that don't match

 

demo

IDmaleraceLocation
11WhiteUS
20AsianJapan
31UnknownSpain
41UnknownJapan

event

IDdatetermgrade
11/2/2010Fever1
14/2/2020Rash2
21/2/2010Fever1
44/1/2011Cold1

 

want:

IDmaleraceLocationevent_yes
11WhiteUS1
20AsianJapan1
31UnknownSpain0
41UnknownJapan1

 

I tried:

proc sql;

select a.*, count(b.ID) as yes_no

from demo a

left join event b on a.ID = b.ID;

 

quit;

 

it works but it shows me sum of all events per ID

2 REPLIES 2
PeterClemmensen
Tourmaline | Level 20
data demo;
input id male race $ Location $;
datalines;
1 1 White US
2 0 Asian Japan
3 1 Unknown Spain
4 1 Unknown Japan
;

data event;
input ID date :mmddyy10. term $ grade;
format date mmddyy10.;
datalines;
1 1/2/2010 Fever 1
1 4/2/2020 Rash 2
2 1/2/2010 Fever 1
4 4/1/2011 Cold 1
;

data want;
   merge demo event(in = e keep = id);
   by id;
   event_yes = e;
run;

 

Result:

 

id male race     Location  event_yes 
1  1    White    US        1 
1  1    White    US        1 
2  0    Asian    Japan     1 
3  1    Unknown  Spain     0 
4  1    Unknown  Japan     1 
novinosrin
Tourmaline | Level 20
data event;
input ID date :mmddyy10. term $ grade;
format date mmddyy10.;
datalines;
1 1/2/2010 Fever 1
1 4/2/2020 Rash 2
2 1/2/2010 Fever 1
4 4/1/2011 Cold 1
;
proc sql;
 create table want as
 select distinct a.*,a.id=b.id as event_yes
 from demo a left join event b
 on a.id=b.id;
quit;
/*Keep term and grade*/
proc sql;
 create table want as
 select a.*,term, grade, a.id=b.id as event_yes
 from demo a left join event b
 on a.id=b.id;
quit;

Notes:

1. a.id=b.id as event_yes /*resolves to a boolean expression 1 or 0 for matches & non matches*/ 

2. You could choose to keep term and grade and that helps to debug later downstream. Anyways, up to 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
  • 2 replies
  • 352 views
  • 1 like
  • 3 in conversation