百分比计算总是 returns me 0 即使值是数字

Percentage calculation always returns me 0 even that the values are numbers

我正在尝试为 table 中的某些错误创建一个百分比。 我构建了一个查询,其中包含每个值的错误数量、错误总数和除法。 但总是给我 0(我添加了一个检查以查看值是否为数字)。

select 
ZZ0010 as Error_type
, qty
, total
,running_sum
, isnumeric(total)
,isnumeric(running_sum)
,running_sum/total

from (
    select ZZ0010
            ,(count(  [ZZ0010] )) as qty
             ,sum(nullif(count(  [ZZ0010] ),0) ) over(order by count(  [ZZ0010] )  desc,ZZ0010) as running_sum 
             ,sum(nullif(count(  [ZZ0010] ),0) ) over() as total
    from md.CAR_CRM_DS_ZCRM_Z101_BUSINESS_ATTR_VT   
    group by ZZ0010
    having (count(  [ZZ0010] )) is not null 
                                                ) tbl
order by running_sum asc
Error_type qty total running_sum isnumeric(total) isnumeric(running_sum) running_sum/total
2 2123 3931 2123 1 1 0
10 1808 3931 3931 1 1 0

嗯。 . .我认为你可以从根本上简化这个:

select ZZ0010,
       count(*) as qty,
       sum(count(*)) over (order by count(*) desc) as running_sum,
       sum(count(*)) over () as total,
       ( sum(count(*)) over (order by count(*) desc) * 1.0 /
         nullif(sum(count(*)) over (), 0)
       ) as ratio
from md.CAR_CRM_DS_ZCRM_Z101_BUSINESS_ATTR_VT   
group by ZZ0010;

备注:

  • 我不知道你为什么要在数字列上使用 isnumeric()
  • COUNT() 不能 return NULL 所以 HAVING 是多余的。
  • 使用 NULLIF() 避免被 0 除。当然,除非所有行都具有 ZZ0010 作为 NULL.
  • ,否则查询中的计数总和不能为零
  • SQL 服务器做整数除法。我只是乘以 1.0 来避免这种情况。
  • NULLIF(COUNT(), 0) 真的很奇怪。为什么在忽略空值的列中区分 0NULL
  • 我不认为子查询在这种情况下特别有用,但如果你不想重复表达式,你当然可以使用子查询。