Louis Ye
Louis Ye

Reputation: 154

Pick value from row when there is overlapping value in another column postgreSQL

Sorry, I am new to SQL so this might be a super dumb question I currently have a table like:

x y
a 12345
b 12345
a 12346
a 12347
a 12348

Is there some simplifying function in sql to always choose b as the value when the y value is the same? Such that it looks something like:

x y
b 12345
a 12346
a 12347
a 12348

Upvotes: 0

Views: 32

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270391

You can use distinct on:

select distinct on (y) t.*
from t
order by y, (x = 'b') desc;

This chooses one row per value with a preference for 'b' over other values.

Upvotes: 1

Related Questions