我有一个这样的表:
date(timestamp) Error(integer) someOtherColumns
我有一个查询来选择特定日期的所有行:
SELECT * from table
WHERE date::date = '2010-01-17'
现在我需要计算 Error 等于 0(从那天开始)的所有行,并将其除以所有行的计数(从那天开始)。
所以结果应该是这样的
Date(timestamp) Percentage of failure
2010-01-17 0.30
数据库相当大,有数百万行..
如果有人知道如何在更多天(从一天到另一天的间隔)中执行此操作,那就太好了。
Date(timestamp) Percentage of failure
2010-01-17 0.30
2010-01-18 0.71
and so on
这个怎么样(如果error
只能是 1 和 0):
select
date,
sum(Error)::numeric / count(Error) as "Percentage of failure"
from Table1
group by date
or, if error
可以是任何整数:
select
date,
sum(case when Error > 0 then 1 end)::numeric / count(Error) as "Percentage of failure"
from Table1
group by date
才发现我数过了not 0
(假设错误是当 Error != 0 时),并且没有考虑空值(不知道你想如何处理它)。因此,这是另一个查询,它将 null 视为 0,并以两种相反的方式计算失败百分比:
select
date,
round(count(nullif(Error, 0)) / count(*) ::numeric , 2) as "Percentage of failure",
1- round(count(nullif(Error, 0)) / count(*) ::numeric , 2) as "Percentage of failure2"
from Table1
group by date
order by date;
sql fiddle demo http://sqlfiddle.com/#!12/a08ef/10
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)