检查重复的行是否在任何行的一个属性中都有值

Car*_*nte 0 sql postgresql

我有一个看起来像这样的表:

ID  | Position
--------------
 1  |    0
 1  |    3
 1  |    5
 2  |    1
 2  |    2
 3  |    1
 3  |    5
Run Code Online (Sandbox Code Playgroud)

我想为每个ID提取一个包含特定值的值。

在这种情况下,如果该值为5,则需要一个这样的表:

ID  | HasNumber
---------------
 1  |  true
 2  |  false
 3  |  true
Run Code Online (Sandbox Code Playgroud)

关于如何解决的任何解决方案或提示?谢谢。

a_h*_*ame 5

您可以使用分组依据和条件计数:

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

另一种选择是使用bool_or()聚合:

select id, bool_or(position = 5) as has_number
from the_table
group by id;
Run Code Online (Sandbox Code Playgroud)