在sql count上进行数学运算

时间:2018-02-11 23:42:39

标签: sql sql-server sql-server-2008

我正在尝试对两个查询的结果进行一些数学运算。

这是我的疑问:

select (x.failed/y.total) * 100 as failure_rate, x.failed, y.total
from
(
select count(*) as failed from status where cast(ins As Date) = cast(getDate() As Date) and fail_flg = 'Y'
) x
join 
(
select count(*) as total from status where cast(ins As Date) = cast(getDate() As Date)
) y on 1=1

这是我回来的结果:

failure_rate    failed  total
0               1       2

我的失败率应该是50,我哪里错了?我怀疑这个问题出现在我count(*)的某个地方....我需要把它作为一个数字投射到某个地方吗?

1 个答案:

答案 0 :(得分:1)

SQL Server执行整数运算。转换为非整数。我这样做:

select (x.failed * 100.0 /y.total) as failure_rate, x.failed, y.total

我应该补充一点,我会编写没有子查询的查询:

select sum(case when fail_flag = 'Y' then 1 else 0 end) as failed,
       count(*) as total,
       avg(case when fail_flag = 'Y' then 100.0 else 0 end) as failed_rate
from status
where cast(ins As Date) = cast(getDate() As Date) ;

通常,我建议不要在列上执行cast()或任何其他功能。这就排除了索引的使用。但是,SQL Server为cast(as date)提供了一个例外,因此您的代码仍然是索引安全的(或SQL Server的术语中的“sargable”)。