SQL:聚合后如何过滤?

时间:2013-04-02 15:16:01

标签: sql select aggregation

删除不需要聚合的值非常容易。

例如:

SELECT department, SUM(sales) as "Total sales"
FROM order_details
GROUP BY department
HAVING SUM(sales) > 1000;

这将从汇总聚合中排除值小于1000的所有销售。

但是如何在聚合后过滤?

E.g。 WHERE ("Total sales"> 15000)

编辑:具有讽刺意味的是,我只包括HAVING SUM(sales) > 1000;,以防止混淆所需的查询类型;因为我实际上并不想从汇总中排除项目,只返回结果!谢谢,尽管有困惑!

3 个答案:

答案 0 :(得分:16)

您的查询实际上是在做您想要的,而不是您在问题中表达的内容。如果要排除值小于1000的所有销售,则应使用WHERE sales > 1000。但是使用HAVING SUM(sales) > 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

答案 1 :(得分:3)

如果您想过滤价值低于1000的销售,则正确的查询是

SELECT department, sales
FROM order_details
WHERE sales > 1000

如果你想聚合,并且只保留总和超过15000,那么你需要这个查询:

SELECT department, SUM(sales) as TotalSales
FROM order_details
WHERE sales > 1000
GROUP BY department
HAVING SUM(sales) > 15000

答案 2 :(得分:0)

您可以通过选择临时表中的总和,然后从临时表中选择,将其作为两步过程执行:

SELECT department, SUM(sales) as TotalSales
INTO #temp
FROM order_details
GROUP BY department
HAVING SUM(sales) > 1000

SELECT department, TotalSales
FROM #temp
WHERE TotalSales > 15000

DROP TABLE #temp