0

My table :

id role
b f
b s
b g
a s
a f
c f

I want a distinct id but with corresponding role, with this logic:

If g exists select g if not 
if s exists select s if not 
if f exists select f.

Query should yield :

id role
b g
a s
c f

I tried group by id, but role cannot be sorted in a useful order.

1
  • 1
    Show actual data sample and explain better the logic. The explanation above does really make much sense. Commented Oct 11, 2022 at 19:56

1 Answer 1

1
select  id
       ,role
from    (
        select  *
                ,rank() over(partition by id order by case when role = 'g' then 2 when role = 's' then 1 end desc) as rnk
        from    t
        ) t
where   rnk = 1
id role
a s
b g
c f

Fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.