I am using SQL Server 2005, and I found weird behavior of the HAVING clause.
By definition the HAVING clause is supposed to work on data after it has been grouped. However using the COUNT function inside a HAVING clause is actually applied on data before it is grouped.
What I am missing here??
Sample data:
DECLARE @ProductTypeIDsTable TABLE
(
A INT
)
INSERT INTO @ProductTypeIDsTable(A) VALUES
(10),(12),(12),(9),(9),(9)
DECLARE @IDsTable TABLE
(
B INT
)
INSERT INTO @IDsTable(B) VALUES
(9),(10),(12)
The query in question:
SELECT A
FROM @ProductTypeIDsTable pt
INNER JOIN @IDsTable ids ON pt.A = ids.B
GROUP BY A
--HAVING COUNT (A) = 1 -- gives 10 (repeated once due to the join)
--HAVING COUNT (A) = 2 -- gives 12 (repeated twice due to the join)
HAVING COUNT (A) = 3 -- gives 9 (repeated thrice due to the join)
Using the aggregate function
countwill not give you different results if you use it in the field list or in the having clause.A regular group by on
A:Result:
If you use
countin thehavingclause this value is what you are comparing against.If you are interested in the count of rows returned after
group byyou can put your query in a sub-query like this:Result:
Update:
From HAVING (Transact-SQL)
From COUNT (Transact-SQL)