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

Dear All:

Could you please tell me how to count a variable only if certain criteria is met in the proc sql syntax.  For example, I want to count both people and Hispanic people.  So I coded the following way, but the calculated p_count and chm_count is the same.  Also, if I want to count rows in which certain variable called sex is F, could I go for count(sex = "F")?

My old but stupid way is to use proc sql two time with the where statement and then join these two tables.  That is not cool.

Thanks!

proc sql;

     create table ipums2 as

           select distinct year, statefip, county, count(pid) as p_count, count(race=4) as hs_count

                from ipums

                     group by year, statefip, county

                           order by year, statefip, county;

quit;

1 ACCEPTED SOLUTION

Accepted Solutions
Tom
Super User Tom
Super User

Since SAS evaluates boolean expressions to 1/0 you can just change the second COUNT() to SUM().

View solution in original post

2 REPLIES 2
LinusH
Tourmaline | Level 20

I don't know what your final result should be (in what form). In many cases, just adding your column to the group by clause is sufficient. If you want specific grouping, you can hold these in control tables (and apply them using SAS formats or SQL join). Adding specific criteria as a basic technique can lead to hard coded programs which lead higher maintenance costs.

Having that said, you could combine case with aggregation functions:

sum(case race when 4 then 1 else 0 end) as hs_count

Data never sleeps
Tom
Super User Tom
Super User

Since SAS evaluates boolean expressions to 1/0 you can just change the second COUNT() to SUM().

sas-innovate-2024.png

Don't miss out on SAS Innovate - Register now for the FREE Livestream!

Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.

 

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.

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
  • 55435 views
  • 5 likes
  • 3 in conversation