Rewrite the count query properly