Desu235
Desu235

Reputation: 1

Get percentages in query

enter image description here

Thank you for your assistance.

I can't get it to divide? Is it because its the Modulo operator? I've reviewed and scoured the web for a bit, but it just doesn't seem to be working. How do I get a percentage in SQL Server. I attempting to divide, but it just spits out nothing.

Upvotes: -1

Views: 65

Answers (1)

Paul Maxwell
Paul Maxwell

Reputation: 35603

Don't abuse select distinct, there is simply no need for it here (and in many many other cases, use sparingly).

Also, it is not necessary to run 3 separate subqueries to arrive at the figures you need. Instead use "conditional aggregates" which is basically putting a case expression inside the aggregation function.

Then, a quick fix for the integer division problem is to explicitly convert integers to decimals, or implicitly make into decimals by using multiplication by a decimal e.g

select
      count(case when Gender = 'Male' then 1 end) as male_count
    , count(case when Gender = 'Female' then 1 end) as female_count
    , count(*) as total_count
    , count(case when Gender = 'Male' then 1 end) * 100.0 / count(*) as male_pct
    , count(case when Gender = 'Female' then 1 end) * 100.0 / count(*) as female_pct
from MedMal85

Upvotes: 1

Related Questions