2017-07-12 37 views
0

好吧我有一个查询,我需要省略结果,如果array_agg =自然的第一个值,所以我想我可以这样做:如果我不能在where子句中使用聚合,如何获得结果

select 
    visitor_id, 
    array_agg(code 
    order by session_start) codes_array 
from mark_conversion_sessions 
where conv_visit_num2 < 2 
    and max_conv = 1 
    and (array_agg(code 
    order by session_start))[1] != 'natural' 
group by visitor_id 

但是当我运行此我得到的错误:

ERROR: aggregate functions are not allowed in WHERE 
LINE 31: and (array_agg(code 

那么,有没有一种方法,我可以引用ARRAY_AGG在where子句中?

谢谢

+3

使用'having' https://www.postgresql.org/docs/current/static/queries- table-expressions.html#QUERIES-GROUP –

+2

尝试使用group by和having子句。 http://www.dofactory.com/sql/having – Nidhi257

+0

其中过滤器行,具有过滤器组。 – Mihai

回答

1

having子句用于像在分组数据where条款。移动正在使用聚集到具有子句的标准,例如:

select 
    visitor_id, 
    array_agg(code order by session_start) codes_array 
from mark_conversion_sessions 
where 
    conv_visit_num2 < 2 
    and max_conv = 1 
group by visitor_id 
having 
    (array_agg(code order by session_start))[1] != 'natural' 

文档: https://www.postgresql.org/docs/9.6/static/tutorial-agg.html

+0

这正是我所需要的。谢谢! –