## Percentange Calculation in SQL

Solved
Regular Contributor
Posts: 185

# Percentange Calculation in SQL

How can we calculate unique count percentage and normal percentage by a group?

data test;

input Q1 Q2 Q3 Q4 Q5 Age BU;

cards;

1 5 2 3 4 3 3

4 5 2 1 2 1 3

2 4 4 3 2 3 2

1 3 2 5 3 2 3

1 2 4 2 1 2 2;

run;

The following program calculates unique count and count for Q1 by Age.

proc sql noprint;

create table file1 as

select Age,Count(Distinct Q1) as Unique, Count(Q2) as Count

from test

group by Age;

quit;

 Age Unique Count Unique % % 1 1 1 25% 20% 2 1 2 25% 40% 3 2 2 50% 40%

I am unable to calculate percentage for these two columns. Refer the table above. The percentage is count for each case by total values. Is it possible via data step or PROC SQL?

Accepted Solutions
Solution
‎07-19-2014 05:07 PM
Posts: 1,270

## Re: Percentange Calculation in SQL

proc sql;
create table file1 as
select Age,Count(Distinct Q1) as Uniq, Count(Q2) as Count
from test
group by Age;
quit;

proc sql;
select age,uniq,count,(uniq/(select sum(uniq) from file1)) as unique_percent,(count/(select sum(count) from file1)) as cnt_percent
from file1;
quit;

All Replies
Posts: 3,215

## Re: Percentange Calculation in SQL

proc report / tabulate ....

---->-- ja karman --<-----
Solution
‎07-19-2014 05:07 PM
Posts: 1,270

## Re: Percentange Calculation in SQL

proc sql;
create table file1 as
select Age,Count(Distinct Q1) as Uniq, Count(Q2) as Count
from test
group by Age;
quit;

proc sql;
select age,uniq,count,(uniq/(select sum(uniq) from file1)) as unique_percent,(count/(select sum(count) from file1)) as cnt_percent
from file1;
quit;

Posts: 5,484

## Re: Percentange Calculation in SQL

I don't understand what this is about but you seem to want something like:

proc sql;

select

age,

daQ1 label="Q1 Unique",

caQ1 label="Q1 Count",

daQ1/dQ2 label="Unique Q1/Q2" format=percent6.1,

caQ1/cQ2 label="Count Q1/Q2" format=percent6.1

from

(select age, count(distinct Q1) as daQ1, count(Q1) as caQ1

from test

group by age),

(select count(distinct Q2) as dQ2, count(Q2) as cQ2 from test);

quit;

PG

PG
Posts: 3,215

## Re: Percentange Calculation in SQL

This question has been asked many times before like: https://communities.sas.com/message/115464 , https://communities.sas.com/thread/30943

If you are new to SAS my preference is leaving out any restriction learning all the possibilities with their advantages and disadvantages.
As SAS is more as just a data-step or SQL language I made the reference to procedures, there are several of them.

Reviewing the options with proc means it is remarkable what you can do with that. Base SAS(R) 9.4 Procedures Guide, Second Edition

---->-- ja karman --<-----
🔒 This topic is solved and locked.