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: Call for Content

Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!

Submit your idea!

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
  • 514 views
  • 2 likes
  • 3 in conversation