postgreSQL错误中WHERE子句中不允许聚合

时间:2014-01-30 19:48:26

标签: sql postgresql join aggregate-functions

我试图执行以下查询,并且我是编写SQL查询的初学者,我想知道如何在WHERE子句中实现以下聚合函数功能。对我来说,任何帮助对我来说都是一个很好的学习曲线。

 select a.name,a.add,a.mobile from user a
     INNER JOIN user_info aac
        ON aac.userid= a.userid  
     INNER JOIN info ac 
        ON aac.infoid= ac.infoid  
    WHERE a.total < 8* AVG(ac.total) 
 GROUP BY a.name, a.add, a.mobile;

这是我在PostgreSQL中遇到的错误:

ERROR:  aggregates not allowed in WHERE clause
LINE 1: ...infoid = ac.infoid where a.total < 8* AVG(ac.tot...
                                                             ^

********** Error **********

ERROR: aggregates not allowed in WHERE clause
SQL state: 42803
Character: 190

我是否想使用Having子句来获得结果?任何对此的更正都将是一个很大的帮助!

1 个答案:

答案 0 :(得分:2)

您可以使用子查询中的窗口函数执行此操作:

select name, add, mobile
from (select a.name, a.add, a.mobile, total,
             avg(ac.total) over (partition by a.name, a.add, a.mobile) as avgtotal, a.total
      from user a INNER JOIN
           user_info aac
           ON aac.userid= a.userid INNER JOIN
           info ac 
           ON aac.infoid= ac.infoid
     ) t
WHERE total < 8 * avgtotal
GROUP BY name, add, mobile;