删除不需要聚合的值非常容易.
例如:
SELECT department,SUM(sales) as "Total sales" FROM order_details GROUP BY department HAVING SUM(sales) > 1000;
这将从汇总聚合中排除值小于1000的所有销售.
但是如何在聚合后过滤?
例如. WHERE(“总销售额”> 15000)
编辑:具有讽刺意味的是,我只包括HAVING SUM(销售)> 1000;为了防止混淆所需的查询类型;因为我实际上并不想从汇总中排除项目,只返回结果!谢谢,尽管困惑!
解决方法
您的查询实际上是在做您想要的而不是您在问题中表达的内容.如果要排除值小于1000的所有销售,则应使用WHERE sales> 1000.但是HAVING SUM(销售)> 1000过滤实际上是在聚合之后完成的.
编写子查询并在原始查询之上添加另一个SELECT WHERE是多余的.
请参阅fiddle以获得澄清.
#Query1 SELECT department,SUM(sales) as Total FROM order_details GROUP BY department HAVING Total > 40; #Query 2 SELECT department,SUM(sales) as Total FROM order_details GROUP BY department HAVING SUM(sales) > 40; #Query 3 SELECT department,SUM(sales) as Total FROM order_details WHERE sales > 40 GROUP BY department; #Query 1 and 2 are the same,filtering after aggregation #Query 3 is filtering before aggregation