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

Hi, 

 

I have the dataset "have" where I want to create a new variable. 

The new variable should count observations with the same ID. I have:

 

IDGPSOpenStore
189503Y1
112353Y1
106834N2
295736N2
201475Y3
364758Y4

 

The new variable count should be like:

 

IDGPSOpenStoreCount
189503Y13
112353Y13
106834N23
295736N22
201475Y32
364758Y41

 

Hope you can help me! Thank you. 

 

Kind regards MM

1 ACCEPTED SOLUTION

Accepted Solutions
novinosrin
Tourmaline | Level 20

data have;
input ID	GPS $	Open $	Store;
cards;
1	89503	Y	1
1	12353	Y	1
1	06834	N	2
2	95736	N	2
2	01475	Y	3
3	64758	Y	4
;

proc sql;
create table want as
select *, count(id) as count
from have
group by id
order by id,store;
quit ;

View solution in original post

4 REPLIES 4
novinosrin
Tourmaline | Level 20

data have;
input ID	GPS $	Open $	Store;
cards;
1	89503	Y	1
1	12353	Y	1
1	06834	N	2
2	95736	N	2
2	01475	Y	3
3	64758	Y	4
;

proc sql;
create table want as
select *, count(id) as count
from have
group by id
order by id,store;
quit ;
ed_sas_member
Meteorite | Level 14

Hi @Mikkel_madsen 

You can use a PROC SQL for example:

proc sql;
	create table want as
	select *, count(*) as count
	from have
	group by id;
run;

Best,

novinosrin
Tourmaline | Level 20

Hi @Mikkel_madsen  I am sharing another smart stuff taught by genius @mkeintz  to whom I owe a lot of my learning


data have;
input ID	GPS $	Open $	Store;
cards;
1	89503	Y	1
1	12353	Y	1
1	06834	N	2
2	95736	N	2
2	01475	Y	3
3	64758	Y	4
;

data want;
 set have(in=a) have(in=b);
 by id;
 retain count;
 if first.id then count=0;
 if a then count=sum(count,1);
 if b;
run;
mkeintz
PROC Star

And, in the pursuit of terminal cuteness, one can: 

 

data have;
input ID	GPS $	Open $	Store;
cards;
1	89503	Y	1
1	12353	Y	1
1	06834	N	2
2	95736	N	2
2	01475	Y	3
3	64758	Y	4
;

data want;
 set have(in=countme) have(in=keepme);
 by id;
 if first.id then count=0;
 count+countme;
 if keepme;
run;

Sorry ... couldn't resist. 

--------------------------
The hash OUTPUT method will overwrite a SAS data set, but not append. That can be costly. Consider voting for Add a HASH object method which would append a hash object to an existing SAS data set

Would enabling PROC SORT to simultaneously output multiple datasets be useful? Then vote for
Allow PROC SORT to output multiple datasets

--------------------------

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!

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
  • 4 replies
  • 1054 views
  • 4 likes
  • 4 in conversation