Hello everyone, I have a large dataset that looks like this:
data have;
input customerID product;
datalines;
A1 P4
A1 P6
A1 P2
A2 P3
A2 P4
A3 P1
;
I want to get a count of how many products each customerID has assigned to it. Each row is unique so there is no need to account for duplicates.
This is what I'm trying to achieve:
data want; input customerID product count; datalines; A1 P4 3 A1 P6 3 A1 P2 3 A2 P3 2 A2 P4 2 A3 P1 1 ;
If the data are sorted by customerid:
data want;
set have (in=firstpass) have (in=secondpass);
by customerid;
if first.customerid then count=0;
count + firstpass;
if secondpass;
run;
data have;
input customerID $ product $;
datalines;
A1 P4
A1 P6
A1 P2
A2 P3
A2 P4
A3 P1
;
run;
proc SQL;
Create table want as
select customerID,
product,
count(1) as count
from have
group by customerID;
Quit;
If the data are sorted by customerid:
data want;
set have (in=firstpass) have (in=secondpass);
by customerid;
if first.customerid then count=0;
count + firstpass;
if secondpass;
run;
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!
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.