我有一个这样的表:
date(timestamp) Error(integer) someOtherColumns
我有一个查询来选择特定日期的所有行:
SELECT * from table
WHERE date::date = '2010-01-17'
现在我需要计算错误等于 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
或者,如果 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 时),并且没有考虑空值(不知道你想如何处理它)。所以这是另一个查询,它将空值视为 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 - 从一个选择中除以两个计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19495096/