DATA Step, Macro, Functions and more

Merging/Joining Datasets

Accepted Solution Solved
Reply
Frequent Contributor
Posts: 123
Accepted Solution

Merging/Joining Datasets

Here is my sample data:

 

 

data a;
  input ZIP Member_Count;
datalines;
1254 234
9936 123
7529 454
9154 678
;
run;

data b;
  input ZIP Member_Count;
datalines;
2156 555
9936 433
3346 225
9154 782
;
run;

data c;
  input ZIP Script_Count;
datalines;
2156 232
2299 656
2222 222
9154 690
;
run;

data d;
  input ZIP Script_Count;
datalines;
2156 555
9936 433
9154 225
2290 782
;
run;

 

And here is what I want:

 

 

data want;
  input ZIP amember bmember cscripts dscripts;
datalines;
1254 234 . . .
9936 123 433 . 433
7529 454 . . .
9154 678 782 690 225
2156 . 555 232 555
2299 . . 656 .
2222 . . 222 .
2290 . . . 782
3346 . 225 . .
;;
run;

 

Basically, I want to combine the data from each dataset but keep distinct ZIP Codes and put values for each zip in columns after it.

 The order of the ZIPS in the output dataset doesn't matter.


Accepted Solutions
Solution
‎05-24-2017 03:58 PM
Trusted Advisor
Posts: 1,022

Re: Merging/Joining Datasets

Posted in reply to JediApprentice

Why not multiple sorts (with embedded variable renames), and one merge?

 

proc sort data=a (rename=(member_count=amember));
  by zip;
run;
proc sort data=b (rename=(member_count=bmember));
  by zip;
run;
proc sort data=c (rename=(script_count=cscript));
  by zip;
run;
proc sort data=d (rename=(script_count=dscript));
  by zip;
run;

data want;
  merge a b c d;
  by zip;
run;

View solution in original post


All Replies
Super User
Posts: 5,518

Re: Merging/Joining Datasets

Posted in reply to JediApprentice

First, sort each data set by ZIP.  Then combine them:

 

data want;

merge a (rename=(member_count=amember))

   b (rename=(member_count=bmember))

   c (rename=(script_count=cscripts))

   d (rename=(script_count=dscripts));

by zip;

run;

 

It can also be done using SQL, in straightforward fashion if that is your preferred tool.

Solution
‎05-24-2017 03:58 PM
Trusted Advisor
Posts: 1,022

Re: Merging/Joining Datasets

Posted in reply to JediApprentice

Why not multiple sorts (with embedded variable renames), and one merge?

 

proc sort data=a (rename=(member_count=amember));
  by zip;
run;
proc sort data=b (rename=(member_count=bmember));
  by zip;
run;
proc sort data=c (rename=(script_count=cscript));
  by zip;
run;
proc sort data=d (rename=(script_count=dscript));
  by zip;
run;

data want;
  merge a b c d;
  by zip;
run;
☑ This topic is solved.

Need further help from the community? Please ask a new question.

Discussion stats
  • 2 replies
  • 127 views
  • 1 like
  • 3 in conversation