SQL Divide by Two Count()

后端 未结 3 1635
抹茶落季
抹茶落季 2021-01-11 19:03

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

相关标签:
3条回答
  • 2021-01-11 19:06

    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
    
    0 讨论(0)
  • 2021-01-11 19:30

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

    0 讨论(0)
  • 2021-01-11 19:31

    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

    0 讨论(0)
提交回复
热议问题