我有一个看起来像这样的表:
ID | Position -------------- 1 | 0 1 | 3 1 | 5 2 | 1 2 | 2 3 | 1 3 | 5
我想为每个ID提取一个包含特定值的值。
在这种情况下,如果该值为5,则需要一个这样的表:
ID | HasNumber --------------- 1 | true 2 | false 3 | true
关于如何解决的任何解决方案或提示?谢谢。
您可以使用分组依据和条件计数:
select id, count(*) filter (where position = 5) > 0 as has_number from the_table group by id;
另一种选择是使用bool_or()
聚合:
select id, bool_or(position = 5) as has_number from the_table group by id;