Forum Moderators: open

Message Too Old, No Replies

Limit results of query based on COUNT()

Is this possible?

         

designaweb

1:41 am on Mar 17, 2006 (gmt 0)

10+ Year Member



I have built a tool that tracks my keywords, and I was just trying to have a look if I could figure out if a single SQL statement was capable of calculating the conversion rate, which I found out was possible!

SELECT 

((COUNT(bookings.quoteid) / COUNT(referers.keywords)) * 100) AS conversion, 

COUNT(referers.keywords) AS keyword_count,

referers.keywords AS keywords 

FROM quotes 

INNER JOIN referers ON quotes.quoteid = referers.quoteid 

LEFT JOIN bookings ON quotes.quoteid = bookings.quoteid 

WHERE 1 

GROUP BY referers.keywords 

ORDER BY counted DESC 

Now what I tried to do was to add in some extra WHERE clause, that would only return results where the "keyword_count" was higher than 5.

However, "WHERE keyword_count > 5" is false, and so is "WHERE COUNT(referers.keywords) > 5"...

Any guru's around?

designaweb

1:47 am on Mar 17, 2006 (gmt 0)

10+ Year Member



Even though I asked this question myself 5 minutes ago, I thought I might as well post the answer now that my MSN-SQL-guru came online....

.. and try to add "HAVING keyword_count > 5" after the "GROUP BY.. " statement

And yes, that did the trick:

SELECT 

((COUNT(bookings.quoteid) / COUNT(referers.keywords)) * 100) AS conversion, 

COUNT(referers.keywords) AS keyword_count,

referers.keywords AS keywords 

FROM quotes 

INNER JOIN referers ON quotes.quoteid = referers.quoteid 

LEFT JOIN bookings ON quotes.quoteid = bookings.quoteid 

WHERE 1 

GROUP BY referers.keywords 

HAVING keyword_count > 5

ORDER BY counted DESC 

Hope this helps anyone else besides me :)