Postgres:返回百分比的查询

时间:2017-06-08 15:22:12

标签: sql postgresql

我的SQL生锈了。我有一个表记录所有HTTP请求及其状态。我想要做的是创建一个查询,显示结果的百分比,其中status =' 404 NOT FOUND'每天

这是表格的样子

articles=# select * from log limit 1;

             path              |       ip       | method | status |              time          |   id
-------------------------------+----------------+--------+--------+----------------------------+---------
 /article/balloon-goons-doomed | 198.51.100.108 | GET    | 200 OK |     2016-07-01 06:02:39-05 | 1688046

我能够获得这样的原始计数,但不知道如何获得百分比

SELECT date_trunc('day', time) "day", count(*) as count FROM log WHERE 
status='404 NOT FOUND' group by 1 ORDER BY 1;

3 个答案:

答案 0 :(得分:2)

您需要的是conditional aggregation

表格PostgreSQL 9.4,它有一个明确的语法(agg_func(...) FILTER (WHERE <predicate>)):

SELECT   date_trunc('day', time) "day",
         COUNT(*) FILTER (WHERE status = '404 NOT FOUND')::NUMERIC
           / COUNT(*) "not found / total"
FROM     log
GROUP BY 1
ORDER BY 1

对于早期版本,您可以使用CASE表达式进行模拟(您只需要确保CASE表达式的THEN分支始终为非NULL} ;遗漏ELSE分支会在所有其他情况下生成NULL,因此COUNT()将不计算它们:

SELECT   date_trunc('day', time) "day",
         COUNT(CASE WHEN status = '404 NOT FOUND' THEN status END)::NUMERIC
           / COUNT(*) "not found / total"
FROM     log
GROUP BY 1
ORDER BY 1

答案 1 :(得分:0)

可以在子查询中选择总计数吗?

SELECT date_trunc('day', time) as day, count(*) / totalCount.count * 100 as percentage
FROM log,
(
    SELECT count(*) FROM log
) totalCount
WHERE status='404 NOT FOUND' group by 1 ORDER BY 1;

答案 2 :(得分:0)

你可以试试这个: 下面的示例查询将给出总记录数以及满足您条件的记录数。 (这是MYSQL示例)

SELECT
((COUNT * 100)/TOTAL_REC_COUNT) AS PERCENT
FROM
(
SELECT COUNT(*) as TOTAL_REC_COUNT,SUM(CASE WHEN STATUS='404 NOT FOUND' then 1 ELSE 0 END) AS COUNT
FROM test.sample_table
) TMP