【问题标题】:Dividing 2 numbers returns 0 [duplicate]除以 2 个数字返回 0 [重复]
【发布时间】:2014-10-14 22:36:53
【问题描述】:

我正在尝试除以 2 个计数以返回一个百分比。

以下查询返回0

select (
    (select COUNT(*) from saxref..AuthCycle
         where endOfUse is null and addDate >= '1/1/2014') / 
    (select COUNT(*) from saxref..AuthCycle 
         where addDate >= '1/1/2014')
    ) as Percentage

我应该应用演员表吗?

【问题讨论】:

  • 添加1.0 *(或100.0 *),如果它是sql-server。
  • 您使用的是哪个 SQL.. SQL Server ???、mySQL 等...
  • COUNT(*) * 100(或100*(SELECT))作为第一个值。
  • 语法上一切看起来都是正确的。显然不能代表数据本身。考虑切换到使用下面@PatrickHofman 的回答中的 CASE 语句。执行路径会更短,因为只需要一次读取表。

标签: sql sql-server sum


【解决方案1】:

通过将通用条件移到 where 子句可以更简洁:

select sum(case when endOfUse is null then 1 end) * 100.0 / count(*) percentage
from saxref..AuthCycle
where addDate >= '1/1/2014'

注意你也不需要0 的大小写为false,因为sum() 会忽略空值

【讨论】:

    【解决方案2】:

    问题是因为您将 2 个 int 值相除,默认情况下将输出一个 int,因为它采用计算中使用的数据类型来确定输出的数据类型,如果您这样做会很有效这个:

    select 50/100 as result
    

    你得到0.5 输出为0,因为它将它四舍五入为int(没有小数位)。

    如果您指定小数:

    select 50.0/100.0 as result
    

    你会得到0.5 作为小数,你可以乘以 100 得到 50%。

    因此,更新您的语法以乘以 1.0 并将计数转换为小数将为您提供正确的结果:

    select (
    (select COUNT(*) from saxref..AuthCycle where endOfUse is null and addDate >= '1/1/2014')*1.0 / 
    (select COUNT(*) from saxref..AuthCycle where addDate >= '1/1/2014')*1.0
    ) as Percentage
    

    【讨论】:

      【解决方案3】:

      我会做不同的事情,使用两个sums:

      select sum
             ( case
               when endOfUse is null and addDate >= '1/1/2014'
               then 1
               else 0
               end
             )
             * 100.0 -- if you want the usual 0..100 range for percentages
             /
             sum
             ( case
               when addDate >= '1/1/2014'
               then 1
               else 0
               end
             )
             percentage
      from   saxref..AuthCycle
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-20
        • 1970-01-01
        • 2015-07-23
        • 2012-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-10
        相关资源
        最近更新 更多