psql中不存在该列

时间:2018-10-26 18:31:20

标签: sql postgresql column-alias

我正在尝试过滤掉错误率超过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 

谢谢!

2 个答案:

答案 0 :(得分:1)

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子句也更容易。

答案 1 :(得分:0)

问题在于,除非对查询进行分层,否则无法在Col1 Col2 Col3 1 2 3 4 5 6 7 8 9 10 11 12 子句中引用列别名col1

重复条件选项:

WHERE

派生表选项:

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;
相关问题