SQL Divide by Two Count()

21,377

Solution 1

Cast your total count as a number besides integer (DECIMAL?) - the math rounds off.

Solution 2

Cast as something with decimal precision, not Integer. A float or real.

select cast(distinctCount as real)/cast(totalCount as real) * 100.00
   , distinctCount
   , totalCount
from (
 select count(distinct id) as distinctCount
  , count(id) as totalCount
  from Table) as aggregatedTable

Solution 3

Shouldn't that be:

;WITH totalCount AS(
    SELECT 
        CAST(COUNT(id) as Integer)as totalCount
    FROM TABLE_NAME
)
SELECT 
    ((CAST(COUNT(DISTINCT id) as Integer)*100/(SELECT count(*) FROM totalCount))) as 'Percent'
FROM TABLE_NAME

Note the SELECT COUNT(*). Also, you should multiply before you divide, otherwise you'll always get zero

Share:
21,377
Jefe
Author by

Jefe

I'm currently a student at Texas Tech University studying Business Administration with a concentration in Management Information Systems. During the school year, I work on "enterprise level" custom developed web application for the school using ASP.NET. This Summer, I have an internship with ARGO Data Resources working in their Business Intelligence department...

Updated on July 15, 2020

Comments

  • Jefe
    Jefe almost 4 years

    I have the following query, which is trying to figure out the percentage of a certain product compared to the total number of products. IE: [Product Count] / [Total Products] = Percent

    ;WITH totalCount AS(
        SELECT 
            CAST(COUNT(id) as Integer)as totalCount
        FROM TABLE_NAME
    )
    SELECT 
        ((CAST(COUNT(DISTINCT id) as Integer)/(SELECT * FROM totalCount))*100) as 'Percent'
    FROM TABLE_NAME
    

    However, the percent column always returns "0" unless there is only one record. In addition, is there a way to add the totalCount and Select query into one?

    Basically, how do you divide two Count() fields?

  • Jefe
    Jefe almost 15 years
    I don't think so, as the totalCount query only returns one row, so if you add in the COUNT(*) it will return 1 always, instead of the actual total. Thanks for the help though :)
  • Jefe
    Jefe almost 15 years
    Thanks, that worked! It's always the simple things that get you.
  • Philippe Leybaert
    Philippe Leybaert almost 15 years
    okay :-) But multiplying by 100 will certainly solve your problem.
  • Matthew Vines
    Matthew Vines almost 15 years
    Make sure you comment that code. The next developer along may not be as clever as you were.
  • dburges
    dburges almost 15 years
    use decimal never use float or real in a math calculation as they are inexact datatypes and can introduce rounding errors.
  • Joel Mansford
    Joel Mansford almost 15 years
    I usually use an even simpler hack and instead of multiplying by 100 multiply by 100.0