Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Divide by Two Count()

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?

like image 243
Jefe Avatar asked Jul 14 '09 19:07

Jefe


2 Answers

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

like image 96
n8wrl Avatar answered Oct 19 '22 09:10

n8wrl


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
like image 39
Remus Rusanu Avatar answered Oct 19 '22 08:10

Remus Rusanu