Skip to content
Advertisement

Check if repeated row has value in one attribute in any of the rows

I have a table that looks like this:

ID  | Position
--------------
 1  |    0
 1  |    3
 1  |    5
 2  |    1
 2  |    2
 3  |    1
 3  |    5

I would like to extract for each ID if it contains a specific value.

In this case, if that value is 5 I would need a table like this:

ID  | HasNumber
---------------
 1  |  true
 2  |  false
 3  |  true

Any solutions or hints about how could I do it? Thanks.

Advertisement

Answer

You can use group by and conditional counting:

select id, count(*) filter (where position = 5) > 0 as has_number
from the_table
group by id;

Another option is to use the bool_or() aggregate:

select id, bool_or(position = 5) as has_number
from the_table
group by id;
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement