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

I have the following two tables that I want to left join using Proc SQL. One is a table of user ID's, the other are all the sales invoices. 

 

What I want is to join the invoices table onto the user ID table so that the count of invoices shows up in an "invoices" column. My problem is that the user ID's become duplicated. 

 

proc sql;
create table full as
select count(b.invoices) as invoices, b.user_id, b.invoice_date, a.user_id from customers a
LEFT JOIN invoice_db b
on a.user_id=b.user_id
where invoice_date>='01JAN2019'd
GROUP BY a.user_id;
quit;

The output looks like 

1	1607
2	1638
2	1638
1	1665
8	2434
8	2434

 

What I need is

 

1	1607
2	1638
1	1665
8	2434

 

 

1 ACCEPTED SOLUTION

Accepted Solutions
SASKiwi
PROC Star

If you only want one row per customer, what invoice date do you want to read - the earliest or latest? If you want the latest this should work:

 

proc sql;
create table full as
select  a.user_id 
       ,B.*
from customers a
LEFT JOIN 
( select user_id
         ,count(invoices) as invoices
         ,max(invoice_date) as latest_invoice_date
  from invoice_db
  where invoice_date>='01JAN2019'd
  GROUP BY user_id
) as B
on a.user_id=b.user_id
;
quit;

View solution in original post

1 REPLY 1
SASKiwi
PROC Star

If you only want one row per customer, what invoice date do you want to read - the earliest or latest? If you want the latest this should work:

 

proc sql;
create table full as
select  a.user_id 
       ,B.*
from customers a
LEFT JOIN 
( select user_id
         ,count(invoices) as invoices
         ,max(invoice_date) as latest_invoice_date
  from invoice_db
  where invoice_date>='01JAN2019'd
  GROUP BY user_id
) as B
on a.user_id=b.user_id
;
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!

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
  • 1 reply
  • 1969 views
  • 0 likes
  • 2 in conversation