Is the calculation in HAVING and SELECT meaning that it will be executed twice?

Say I have this query:

SELECT CompanyId, COUNT(*) as Total
FROM Customer
GROUP BY CompanyId
HAVING COUNT(*) > 100

I have COUNT(*)two times in my request. Does this mean that it is COUNTexecuted twice?

This is a simple example, but when I have a more complicated calculation (something like SUM(Weight) / COUNT(*)), I am worried that this may affect performance. Or can any performance impact be careless?

I am using MS SQL 2012 and cannot do it HAVING Total > 100.

+4
source share
2 answers

, , . , , , .

, . :

SELECT CompanyId, SUM(Weight) / COUNT(*)
FROM Customer
GROUP BY CompanyId
HAVING SUM(Weight) / COUNT(*) > 100

SUM(Weight) COUNT(*) , ( ). , - , , .

, HAVING SELECT, :

SELECT CompanyId, MAX(Weight), MIN(Weight), COUNT(*) as Total
FROM Customer
GROUP BY CompanyId
HAVING MAX(Weight) > 2 * MIN(Weight) AND AVG(Weight) > 0.5

: MAX(Weight), MIN(Weight), AVG(Weight) COUNT(*). 1 , CompanyId, HAVING, . 2

: , , SQL Server , , . SQL Server 2012 2016, , , , .


  • AVG ; SUM / COUNT(*), , . , MAX, MIN, SUM COUNT.
  • . , , , ( ).
+3

, COUNT(*) , .

.

, , , , , COUNT(*). (COUNT(DISTINCT) ), , .

, :

HAVING Total > 100

/CTE .

+1

Source: https://habr.com/ru/post/1684452/


All Articles