2017-05-19 17 views
1

我有一點麻煩確定哪些天在這裏的地位誤差超過1%是表:Python的PSQL拆分成相應的列

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,並將它們分解爲它們各自的日期,但我不知道如何寫它。

如果有人能幫助我,我將非常感激。

錯誤

File "news.py", line 33 
    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") 
                                     ^
SyntaxError: invalid syntax 

我注意到,當時是在雙引號,所以我改成了單引號,可能是問題,並得到這個錯誤:

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... 
                  ^

回答

1

此查詢應該這樣做:

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 

based on exa mple:

編譯:

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) 
+0

當我試圖執行這個查詢它告訴我沒有在最後那裏 –

+0

請確切的錯誤語法錯誤?因爲查詢在psql中工作 –

+0

即時通訊使用psycopg在python上運行它即時更新我的​​帖子與錯誤,以便它更好地格式化 –