2

我试图过滤掉网站错误率超过 1% 的日子。我已经有一个表格显示了各个日期及其各自的错误率,但是当我尝试包含“where”或“having”子句以过滤掉比率低于 0.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 

谢谢!!

4

2 回答 2

2

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条款。

于 2018-10-26T18:32:42.163 回答
0

问题是您不能col1WHERE子句中引用列别名,除非您对查询进行分层。

重复条件选项:

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
于 2018-10-26T18:44:10.933 回答