Aggregates not allowed in WHERE clause in postgreSQL error

◇◆丶佛笑我妖孽 提交于 2019-12-24 11:44:37

问题


I was trying to execute this following query, and I am a beginner in writing SQL Queries, was wondering how can I achieve the following aggregate functions functionality doing in WHERE clause. Any help on this would be a great learning curve for me.

 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;

And this is the error I am getting in 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

Am I suppose to use Having clause to have the results? any correction on this would be a great help!


回答1:


You can do this with a window function in a subquery:

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;


来源:https://stackoverflow.com/questions/21466123/aggregates-not-allowed-in-where-clause-in-postgresql-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!