问题
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