[英]Column does not exist in psql
我正在嘗試過濾出錯誤率超過1%的網站的日子。 我已經有一個表來顯示各個日期及其各自的錯誤率,但是當我嘗試包括“ where”或“ having”子句以過濾比率低於.01的日期時,查詢將停止工作並顯示即使我之前聲明了幾個字符,我的列也不存在。 這是代碼:
select date(time) as day,
(trunc(cast(count(*) filter (where status similar to '%404%') as decimal) / count(*), 5)) as col1
from log
where col1 > 0.01
group by day
order by col1 desc;
這是我得到的錯誤
ERROR: column "col1" does not exist
LINE 4: where col1 > 0.01
謝謝!!
col1
是聚合的結果。 Postgres允許group by
列的別名,但不能having
。 因此,將條件移至having
子句:
select date(time) as day,
(trunc(cast(count(*) filter (where status similar to '%404%') as decimal) / count(*), 5)) as col1
from log
group by day
having (trunc(cast(count(*) filter (where status similar to '%404%') as decimal) / count(*), 5)) > 0.01
order by col1 desc;
盡管filter
確實很花哨,但我認為此版本的邏輯更簡單:
trunc(cast(avg( (status similar to '%404%')::decimal), 5) as col1
也可以更容易地將它放入having
子句中。
問題是,除非對查詢進行分層,否則無法在WHERE
子句中引用列別名col1
。
重復條件選項:
select date(time) as day,
(trunc(cast(count(*) filter (where status similar to '%404%') as decimal) / count(*), 5)) as col1
from log
group by day
having (trunc(cast(count(*) filter (where status similar to '%404%') as decimal) / count(*), 5)) > 0.01
order by col1 desc;
派生表選項:
select day, col1
from (select date(time) as day,
(trunc(cast(count(*) filter (where status similar to '%404%') as decimal) / count(*), 5)) as col1
from log
group by day) as derivedTable
where col1 > 0.01
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.