sql: clean mixing of by and count(table)