[英]SQL Divide by Two 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
但是,除非只有一條記錄,否則百分比列始終返回“0”。 另外,有沒有辦法將totalCount和Select查詢添加到一個?
基本上,你如何划分兩個Count()字段?
將你的總計數作為除整數之外的數字(DECIMAL?) - 數學四舍五入。
作為具有小數精度的東西,而不是整數。 漂浮或真實。
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
不應該是:
;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(*)。 此外,你應該在划分之前相乘,否則你將總是得到零
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.