我有以下查询,它试图找出某个产品与产品总数相比的百分比。 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
但是,除非只有一条记录,否则百分比列始终返回“0”。另外,有没有办法将totalCount和Select查询添加到一个?
基本上,你如何划分两个Count()字段?
答案 0 :(得分:9)
将你的总计数作为除整数之外的数字(DECIMAL?) - 数学四舍五入。
答案 1 :(得分: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
答案 2 :(得分:2)
不应该是:
;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
注意SELECT COUNT(*)。此外,你应该在分割之前相乘,否则你将总是得到零