Computing Percentages within Subtotals
Problem
You want to analyze answers to a survey question to determine how each state
responded. Then you want to compute the percentage of each answer that a given state
contributed. For example, what percentage of all NO responses came from North
Carolina?
Background Information
There is one input table, called Survey, that contains the following data (the first ten
rows are shown):
data survey;
input State $ Answer $ @@;
datalines;
NY YES NY YES NY YES NY YES NY YES NY YES NY NO NY NO NY NO NC YES
NC YES NC YES NC YES NC YES NC YES NC YES NC YES NC YES NC YES NC YES
NC YES NC YES NC YES NC YES NC YES NC YES NC YES NC YES NC YES NC NO
NC NO NC NO NC NO NC NO NC NO NC NO NC NO NC NO NC NO NC NO
NC NO NC NO NC NO NC NO NC NO NC NO NC NO NC NO NC NO NC NO
NC NO NC NO NC NO PA YES PA YES PA YES PA YES PA YES PA YES PA YES
PA YES PA YES PA NO PA NO PA NO PA NO PA NO PA NO PA NO PA NO
PA NO PA NO PA NO PA NO PA NO PA NO PA NO PA NO PA NO PA NO
VA YES VA YES VA YES VA YES VA YES VA YES VA YES VA YES VA YES VA YES
VA YES VA YES VA YES VA YES VA YES VA YES VA YES VA YES VA YES VA NO
VA NO VA NO VA NO VA NO VA NO VA NO VA NO VA NO VA NO VA NO
VA NO VA NO VA NO VA NO VA NO VA NO
;
proc print data=Survey(obs=10);
title 'Sample Data for Subtotal Percentages';
run;
Computing Percentages within Subtotals 185
Output 6.7 Input Table for Computing Subtotal Percentages (Partial Output)
Solution
Use the following PROC SQL code to compute the subtotal percentages:
proc sql;
title1 'Survey Responses';
select survey.Answer, State, count(State) as Count,
calculated Count/Subtotal as Percent format=percent8.2
from survey,
(select Answer, count(*) as Subtotal from survey
group by Answer) as survey2
where survey.Answer=survey2.Answer
group by survey.Answer, State;
quit;
186 Chapter 6 Practical Problem-Solving with PROC SQL

Get SAS 9.4 SQL Procedure User's Guide, Third Edition, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.