I have a MySQL query like this:
SELECT *, SUM(...some SQL removed for brevety) AS Occurrences FROM some_table AS q WHERE criterion='value' GROUP BY q.P_id ORDER BY Occurrences DESC LIMIT 10;
I want to restrict the results to rows where Occurrences>0. This seems very simple to me, but I can’t seem to make it work. No matter what I try, WHEREs or HAVINGs, whenever I try to add this restriction I get NO ROWS in return. I’m positive that there is data in my table that should be returned. Does anyone know how to accomplish what I’m doing?
I’ve tried this, but it still doesn’t work. Any ideas why it still won’t work?
SELECT *, SUM(...some SQL removed for brevety) AS Occurrences FROM some_table AS q WHERE criterion='value' HAVING SUM(...some SQL removed for brevety)>0 GROUP BY q.P_id ORDER BY Occurrences DESC LIMIT 10;
I am not as familiar with MySQL as I am with SQL Server, but in T-SQL, you can’t use aliases in GROUP BY clauses (I originally thought ORDER BY clauses as well, but that has since been shown to be incorrect). In this case, you want to filter based on the results of a GROUP BY, so I would use a HAVING clause as follows: