Improve count duplicate rows function