我有一个创建的视图,名称为author_article_log,如下所示:
title | name | status | date
Candidate is jerk, alleges rival | Rudolf von Treppenwitz | 200 OK | 2016-07-01
我的工作是获取一天中请求错误的百分比, 我的查询是:
select i.date,
((count (case when i.status = '404 NOT FOUND'
then 1
else 0
end)
* 1.0
/ count (case when i.date = j.date
then 1
else 0
end)
) *100
) as percentage
from author_article_log as i, author_article_log as j
group by i.date, j.date
order by percentage desc;
运行此查询不会返回结果,也不会出现任何错误,有人可以告诉我为什么会这样吗?
答案 0 :(得分:2)
sum()
,而不是count()
注意:COUNT(0)
等于1
DATE
是关键字;最好不要将其用作列名SELECT zdate,
100.0 * SUM (CASE WHEN status = '404 NOT FOUND' THEN 1 ELSE 0 END)
/ COUNT(*) AS percentage
FROM author_article_log
GROUP BY zdate
ORDER BY percentage DESC
;
答案 1 :(得分:0)
您可以尝试使用WITH
子句来过滤您的请求
WITH errors AS (
SELECT date, COUNT(*) AS nb_errs
FROM author_article_log
WHERE status = '404 NOT FOUND'
GROUP BY date
), total AS (
SELECT date, COUNT(*) AS nb_queries
FROM author_article_log
GROUP BY date
)
SELECT e.date, 100.0 * e.nb_errs / t.nb_queries AS percentage
FROM errors e
JOIN total t ON e.date = t.date
ORDER BY percentage DESC
文档:PostgreSQL: Documentation: 10: 7.8. WITH Queries (Common Table Expressions)