获取列总和并用于计算总数的百分比,为什么不适用于 CTE

Get column sum and use to calculate percent of total, why doesn't work with CTEs

我做了以下查询,但是它为每个 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

使用window函数和适当的除法:

select orderstatusName, counts * 1.0 / total_counts
from (select t.*, sum(counts) over () as total_counts
      from tbl
     ) t;

你得到 0 的原因是因为 SQL 服务器在操作数是整数时进行整数除法。所以,1/2 = 0,而不是 0.5。

您正在使用所谓的整数数学。在 SQL(服务器)中使用 2 个整数时,return 值也是一个整数。例如,2 + 2 = 45 * 5 = 25。除法 8 / 10 = 0 也是如此。那是因为 0.8 不是整数,但 return 值将为一(因此小数点丢失)。

更改此行为的常用方法是将其中一个表达式乘以 1.0。例如:

counts/(select sum(counts) * 1.0 from tbl) as PofTotal

如果您需要更高的精度,可以增加 1.0 的小数精度(即 1.0001.0000000 等)。