SQL HAVING Performance

守給你的承諾、 提交于 2020-12-16 04:48:52

问题


Hi I was looking a way to filter an calculated column. I just fund using HAVING.

I was wondering if with the need to repeat the calculation on having and select, my SQL have to calculate two times and consequently have performance impact.

ie:

USE AdventureWorks2012 ;
GO
SELECT SalesOrderID, SUM(LineTotal) AS SubTotal
FROM Sales.SalesOrderDetail
GROUP BY SalesOrderID
HAVING SUM(LineTotal) > 100000.00
ORDER BY SalesOrderID ;

回答1:


The expense in doing the calculation is in arranging the group by. Doing an additional aggregation function adds very, very little overhead compared to arranging the data in groups. In addition, SQL Server may be smart enough to calculate the sum() only once -- I don't know, but it would be a very reasonable optimization.

Note: this is true of the traditional aggregation functions. Some, such as count(distinct) or the statistical functions incur more overhead and you would want to be more careful about calling them multiple times.



来源:https://stackoverflow.com/questions/27565847/sql-having-performance

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