查找表格列的百分比

时间:2018-01-09 12:38:47

标签: sql database postgresql

我有一个包含以下列路径,时间,状态,ID和方法的表。我想选择所有方法都没有' 200 OK'并计算每次向该路径发出请求时的百分比。我尝试过以下方法:

select time as day, 
(count(status) * 100 / (select count(*) from log)) as error 
from log 
where status != '200 OK' group by day;

select time as day,
(count(status) * 100.0 / (select count(*) from log where status != '200OK')) as errors 
from log 
where status != '200 OK' group by time order by errors DESC

我尝试过的查询我并不是100%确定实际计算的内容,所以如果你能提供帮助,请提供查询正在做什么的一些细节。感谢所有帮助的人。下面是几行的表格。我试着尽可能地排好它。

path               |ip             |method| status        |time       |id
/path-to-page-A/   |198.51.100.195 |GET   | 200 OK        |2016-07-01 07:00:00+00| 23 
/path-to-page-B/   |192.0.2.80     |GET   | 404 Not Found |2016-07-01 07:00:00+00| 24
/path-to-page-C/   |192.0.2.81     |GET   | 404 Not Found |2016-07-01 07:00:00+00| 25        
/path-to-page-A/   |198.51.100.195 |GET   | 200 OK        |2016-08-01 07:00:00+00| 26

2 个答案:

答案 0 :(得分:0)

我添加了一行以使其更有趣:

create table log
(
    path      varchar(16),
    ip        varchar(16),
    method    varchar(8),
    status    varchar(16),
    time      timestamp,
    id        integer
);

insert into log(path, ip, method, status, time, id ) values ('/path-to-page-A/','198.51.100.195','GET','200 OK',       '2016-07-01 07:00:00+00', 23); 
insert into log(path, ip, method, status, time, id ) values ('/path-to-page-B/','192.0.2.80',    'GET','404 Not Found','2016-07-01 07:00:00+00', 24);
insert into log(path, ip, method, status, time, id ) values ('/path-to-page-C/','192.0.2.81',    'GET','404 Not Found','2016-07-01 07:00:00+00', 25);       
insert into log(path, ip, method, status, time, id ) values ('/path-to-page-A/','198.51.100.195','GET','200 OK',       '2016-08-01 07:00:00+00', 26);
insert into log(path, ip, method, status, time, id ) values ('/path-to-page-B/','192.0.2.80',    'GET','200 OK',       '2016-07-01 07:00:00+00', 30);

查询:

select
    a.path,
    coalesce(b.failed_requests, 0) * 100 / a.all_requests as percent_failed
from
    (
        select
            path,
            count(*) as all_requests
        from
            log
        group by
            path
    ) a
    left outer join
    (
        select
            path,
            count(*) as failed_requests
        from
            log
        where
            status <> '200 OK'
        group by
            path
    ) b
    on a.path = b.path;

结果:

       path       | percent_failed 
------------------+----------------
 /path-to-page-B/ |             50
 /path-to-page-A/ |              0
 /path-to-page-C/ |            100
(3 rows)

如果您需要更多解释,请随时发表评论。

答案 1 :(得分:0)

您可以使用案例来帮助进行计算。

SELECT path, SUM(CASE WHEN status != '200 OK' THEN 1 ELSE 0 END)/COUNT(path) AS error
FROM log
GROUP BY path