获得每日错误的百分比

时间:2018-04-10 18:29:29

标签: sql database postgresql

我有1个表,其中包含2列我正在使用(时间,状态) 我在时间列中选择date_trunc()的特定日期并应用条件where status = '404 NOT FOUND'

并将其除以每日计数 获得每日错误的百分比

status has 2 values 404 NOT FOUND and 200 OK
--------------------------------------------

我想获得每日错误百分比

我尝试过: select case when status = '404 NOT FOUND' then count(time) END / count(time) from log group by date_trunc('day',time); 但得到错误我得到错误列“log.status”必须出现在GROUP BY子句中或用于聚合函数

2 个答案:

答案 0 :(得分:2)

您可以使用以下内容:

SELECT days, (ERROR*1.0/TOTAL)*100.0 Percentage FROM
(select date_trunc('day',time) days,
    COUNT(case when status = '404 NOT FOUND' 
                   then 1 ELSE NULL END) ERROR,
    COUNT(1) TOTAL
from log
group by date_trunc('day',time)) A;

答案 1 :(得分:0)

我会这样做:

select date_trunc('day', time) as dte,
       avg(case when status <> '200 OK' then 1.0 else 0 end) as daily_rate
from log l
group by dte;

在Postgres中,这可以进一步缩短为:

select date_trunc('day', time) as dte,
       avg( (status <> '200 OK')::int ) as daily_rate
from log l
group by dte;