Stu*_*ler 12 sql select aggregation
删除不需要聚合的值非常容易.
例如:
SELECT department, SUM(sales) as "Total sales"
FROM order_details
GROUP BY department
HAVING SUM(sales) > 1000;
Run Code Online (Sandbox Code Playgroud)
这将从汇总聚合中排除值小于1000的所有销售.
但是如何在聚合后进行过滤?
例如 WHERE ("Total sales"> 15000)
编辑:具有讽刺意味的是,我只是HAVING SUM(sales) > 1000;
为了防止混淆所需的查询类型而被包括在内; 因为我实际上并不想从汇总中排除项目,只返回结果!谢谢,尽管困惑!
jur*_*eza 17
您的查询实际上是在做您想要的而不是您在问题中表达的内容.如果要排除值小于1000的所有销售,则应使用WHERE sales > 1000
.但是HAVING SUM(sales) > 1000
过滤实际上是在聚合之后完成的.
编写子查询并SELECT WHERE
在原始查询之上添加另一个查询是多余的.
请参阅小提琴以获得澄清.
#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
Run Code Online (Sandbox Code Playgroud)