Python psql被拆分为相应的列
在确定哪一天的状态错误超过1%时,我遇到了一些麻烦,如下表所示:Python psql被拆分为相应的列,python,postgresql,psql,Python,Postgresql,Psql,在确定哪一天的状态错误超过1%时,我遇到了一些麻烦,如下表所示: path | text | ip | inet | method | text | status | text | time | timestamp with time zone | default now() id | integer
path | text |
ip | inet |
method | text |
status | text |
time | timestamp with time zone | default now()
id | integer | not null default nextval('log_id_seq'::regclass)
Indexes:
"log_pkey" PRIMARY KEY, btree (id)
重要的部分是状态,它要么是200 OK,要么是一个错误,时间就是日期,其余的部分对于这个特殊的问题我相信是没用的
这是我到目前为止的代码:
def heavy_error_days():
db = psycopg2.connect("dbname=news")
c = db.cursor()
c.execute("select date(log.time), errors\
from log, (select count(status)::numeric/(select count(status)\
from log)from log where status <> '200 OK'\
and date(log.time) = date(log.time)) as errors\
group by date, errors")
print c.fetchone()
我相信我需要做的是把错误乘以100,然后把它们分成各自的日期,但我不知道怎么写
如果有人能帮我,我将非常感激
错误
我注意到时间是用双引号括起来的,这可能是问题所在,所以我将其改为单引号,并得到以下错误:
Traceback (most recent call last):
File "news.py", line 41, in <module>
heavy_error_days()
File "news.py", line 33, in heavy_error_days
c.execute("with a as (select distinct (sum(case when status <> '200 OK' then 1 else 0 end) over w * 100) / count(1) over w perc, 'time'::date d from log window w as (partition by 'time'::date))select * from a where perc > 1")
psycopg2.DataError: invalid input syntax for type date: "time"
LINE 1: ...else 0 end) over w * 100) / count(1) over w perc, 'time'::da...
^
此查询应实现以下功能:
with a as (
select distinct (sum(case when status <> '200 OK' then 1 else 0 end) over w * 100) / count(1) over w perc, "time"::date d
from log
window w as (partition by "time"::date)
)
select *
from a
where perc > 1
查询:
t=# with a as (
select distinct (sum(case when status <> '200 OK' then 1 else 0 end) over w * 100) / count(1) over w perc, "time"::date d
from log
window w as (partition by "time"::date)
)
select *
from a
where perc >= 0
;
perc | d
------+------------
0 | 2017-05-17
33 | 2017-05-19
(2 rows)
当我尝试执行这个查询时,它告诉我上一次在python上使用psycopg运行它时出现了语法错误,我将用这个错误更新我的帖子,这样会更好formatted@DanielCampos我检查了错误-您必须转义双引号才能\time \-仅将双引号更改为单引号会更改整个查询。“时间”是文字,时间是标识符——它不仅仅是任何引号
t=# create table log("time" timestamptz, status text);
CREATE TABLE
t=# insert into log values (now(),'200 OK'),(now(),'200 OK'),(now(),'ERR'),(now()-'2 days'::interval,'200 OK');
INSERT 0 4
t=# with a as (
select distinct (sum(case when status <> '200 OK' then 1 else 0 end) over w * 100) / count(1) over w perc, "time"::date d
from log
window w as (partition by "time"::date)
)
select *
from a
where perc >= 0
;
perc | d
------+------------
0 | 2017-05-17
33 | 2017-05-19
(2 rows)