tags:

views:

62

answers:

3

WHERE gets processed before GROUP BY in the SELECT statement. How can I use WHERE on the result of a COUNT(name)?

What I want is this:

SELECT topic, COUNT(name) AS counter
FROM blah
GROUP BY name
WHERE counter <> 1
+9  A: 
SELECT topic, COUNT(name) AS counter
FROM blah
GROUP BY topic
HAVING COUNT(name) <> 1
shahkalpesh
Shouldn't that be `GROUP BY topic`?
markusk
@markusk: +1. Yes, you are right. I have corrected the SQL.
shahkalpesh
+6  A: 

I think you are looking for Having Clause:

http://msdn.microsoft.com/en-us/library/ms180199.aspx

SELECT topic, COUNT(name) AS counter
FROM blah
GROUP BY topic
HAVING COUNT(name) <> 1
Nitin Midha
+1  A: 

as the other have answered you need a HAVING.

WHERE filters the rows remaining after all joins

GROUP BY combines rows into groups

HAVING filters those groups

don't worry abut repeating the COUNT(*) in the SELECT list and the having, the optimizer is smart enough to optimize this of most databases

anonymous user