SQL除以两个计数()

Jef*_*efe 10 sql sql-server count

我有以下查询,它试图找出某个产品与产品总数相比的百分比.IE:[产品数量]/[总产品数量] =百分比

;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
Run Code Online (Sandbox Code Playgroud)

但是,除非只有一条记录,否则百分比列始终返回"0".另外,有没有办法将totalCount和Select查询添加到一个?

基本上,你如何划分两个Count()字段?

n8w*_*wrl 10

将你的总计数作为除整数之外的数字(DECIMAL?) - 数学四舍五入.

  • 确保您评论该代码.下一个开发人员可能不像你那么聪明. (2认同)
  • 我通常使用更简单的黑客而不是乘以100乘以100.0 (2认同)

Rem*_*anu 5

作为具有小数精度的东西,而不是整数.漂浮或真实.

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
Run Code Online (Sandbox Code Playgroud)