Fix n_count SQL query to count items. Closes #517