some refactoring, correct sql query on count