BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
abdulla
Pyrite | Level 9

Table X

gvkeyfyearName
10041994a
10041995a
10041996b
10041997b

Table Y

gvkeyfyearName
10041992a
10041993a
10041996e
10041997f

 

I want to merge the above two tables in the following way

gvkeyfyearName
10041992a
10041993a
10041994a
10041995a
10041996b
10041997b

You can see that I want every observation from table X but from table Y I want only those observations that matches GVKEY but don't match fyear. From table Y if gvkey and year matches, I don't want those observations to be included in my result. Can anyone help me with how I can do this by using proc SQL? I tried to do that using left join but I don't get the desired result. 

 

1 ACCEPTED SOLUTION

Accepted Solutions
Ksharp
Super User
data X;
infile cards expandtabs truncover;
input gvkey	fyear	Name $;
cards;
1004	1994	a
1004	1995	a
1004	1996	b
1004	1997	b
;

data Y;
infile cards expandtabs truncover;
input gvkey	fyear	Name $;
cards;
1004	1992	a
1004	1993	a
1004	1996	e
1004	1997	f
;

proc sql;
create table want as
select * from x
union all
select * from y 
 where not exists(select * from x where gvkey=y.gvkey and fyear=y.fyear)
order by 1,2;
quit;

View solution in original post

2 REPLIES 2
ChrisNZ
Tourmaline | Level 20

This works for your sample:

 

data HAVE;
  merge Y X;
  by GVKEY FYEAR ;
run;
Obs gvkey fyear Name
1 1004 1992 a
2 1004 1993 a
3 1004 1994 a
4 1004 1995 a
5 1004 1996 b
6 1004 1997 b

 

 

Ksharp
Super User
data X;
infile cards expandtabs truncover;
input gvkey	fyear	Name $;
cards;
1004	1994	a
1004	1995	a
1004	1996	b
1004	1997	b
;

data Y;
infile cards expandtabs truncover;
input gvkey	fyear	Name $;
cards;
1004	1992	a
1004	1993	a
1004	1996	e
1004	1997	f
;

proc sql;
create table want as
select * from x
union all
select * from y 
 where not exists(select * from x where gvkey=y.gvkey and fyear=y.fyear)
order by 1,2;
quit;

SAS Innovate 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 2 replies
  • 535 views
  • 2 likes
  • 3 in conversation