consider my sql query below; it is calling sum twice for the same argument. IS this duplicating the work done by the server. Is there a better way to do this?
SELECT Status_Detail_Code, count(*) as
[Number of times assigned], round(sum(Duration)/60,2) as [total duration Hr]
FROM dbo.V_TIMELINE
WHERE (CADATE > N'20080101')
group by Status_Detail_Code order by sum(Duration) desc
No,
SQL Serverreuses the aggregates.In fact, if you build the query plan, you will see the
SUMin a result set of an aggregation operator (likeStream Aggregate) denoted as something likeExpr****.The value of this expression will later be used as an input to the other operators.
Here’s the sample query:
and it’s plan:
As you can see, the aggregation is done once and stored in
Expr1003.Expr1003is then reused in both theSortoperator (which processes theORDER BY) andCompute Scalar(which processesROUND)