我做了以下查询,但是它为每个 orderStatusName 提供了 0 的结果,有人知道问题出在哪里吗?
with tbl as (
select s.orderstatusName, c.orderStatusId,count(c.orderId) counts
from [dbo].[ci_orders] c left join
[dbo].[ci_orderStatus] s
on s.orderStatusId = c.orderStatusId
where orderedDate between '2018-10-01' and '2018-10-29'
group by orderStatusName, c.orderStatusId
)
select orderstatusName, counts/(select sum(counts) from tbl as PofTotal) from tbl
结果是:0
最佳答案
您正在使用所谓的整数数学。在 SQL (Server) 中使用 2 个整数时,返回值也是一个整数。例如,2 + 2 = 4
、5 * 5 = 25
。这同样适用于除法 8/10 = 0
。这是因为 0.8
不是整数,但返回值将为 1(因此小数点丢失)。
更改此行为的常用方法是将其中一个表达式乘以 1.0
。例如:
counts/(select sum(counts) * 1.0 from tbl) as PofTotal
如果您需要更高的精度,您可以增加1.0
的小数值的精度(即到1.000
、1.0000000
等) .
关于sql - 获取列总和并用于计算总数的百分比,为什么不适用于 CTE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53049420/