How to get either first row or last row of repeating values fast