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

Suppose I have a SAS table as follows:

 

ID   Yr

A    2003

A    2004

A    2004

B    2003

B    2003

 

I would like to add a new column which has the number of occurrences of each ID as follows:

 

ID   Yr       Occurences

A    2003   3

A    2004   3

A    2004   3

B    2003   2

B    2003   2

 

Please advise on how I can do this

1 ACCEPTED SOLUTION

Accepted Solutions
novinosrin
Tourmaline | Level 20


data have;
input ID $   Yr;
cards;
A    2003

A    2004

A    2004

B    2003

B    2003
;

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

View solution in original post

3 REPLIES 3
novinosrin
Tourmaline | Level 20


data have;
input ID $   Yr;
cards;
A    2003

A    2004

A    2004

B    2003

B    2003
;

proc sql;
 create table want as
 select *, count(*) as occurences
 from have
 group by id
 order by id, yr;
quit;
novinosrin
Tourmaline | Level 20
data want;
 do _n_=1 by 1 until(last.id);
  set have;
  by id;
  occurences=sum(occurences,1);
 end;
 do _n_=1 to _n_;
  set have;
  output;
 end;
run;
aalluru
Obsidian | Level 7

That worked perfectly. Thank you so much!

sas-innovate-2026-white.png



April 27 – 30 | Gaylord Texan | Grapevine, Texas

Registration is open

Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!

Register now

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
  • 3 replies
  • 1992 views
  • 0 likes
  • 2 in conversation