【问题标题】:Percentage calculation always returns me 0 even that the values are numbers [closed]即使值是数字,百分比计算也总是返回 0 [关闭]
【发布时间】:2021-06-18 19:21:14
【问题描述】:

我正在尝试为我的表格中的一些错误创建一个百分比。 我构建了一个查询,其中包含每个值的错误数量、总错误和除法。 但是总是给我 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

【问题讨论】:

  • 整数除法。乘以1.0 将其更改为小数running_sum * 1.0 / total
  • 你是对的!如此简单的解决方案!谢谢!

标签: sql sql-server tsql integer-division


【解决方案1】:

嗯。 . .我认为您可以从根本上简化这一点:

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() 不能返回 NULL 所以 HAVING 是多余的。
  • 使用NULLIF() 避免被0 除。当然,除非所有行都将ZZ0010 设为NULL,否则查询中的计数总和不能为零。
  • SQL Server 执行整数除法。我只是乘以 1.0 来避免这种情况。
  • NULLIF(COUNT(), 0) 真的很奇怪。为什么要在忽略空值的列中区分0NULL
  • 我不认为子查询在这种情况下特别有用,但如果您不想重复表达式,当然可以使用子查询。

【讨论】:

    猜你喜欢
    • 2018-08-04
    • 2018-11-22
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    相关资源
    最近更新 更多