I have below dataset with comments which row must be returned. Logic is: return value for max kg_to within partition of each country. Current working code: Question: Shorter code would be better, any ideas on how to improve it? Answer Use distinct on: Or window functions: Note: I also don’t see how your code could be retrieving duplicates, unless you