[英]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.