Postgres 分组至少有 1 行 status='started'

Postgres group by having at least 1 row with status='started'

我需要执行分组依据,并且仅在至少有一个观察与约束匹配时才包括在内。就像我在下面试图描述的那样。

SELECT {some variables}
FROM my_table
GROUP BY A
HAVING {at least 1 row with status='started'}

我最初猜测要替换的是“至少有 1 行状态='started'”是“bool_or(status= 'started')”。哪个不行。

你们有什么建议吗?

编辑:

SELECT {some variables}
FROM my_table
GROUP BY A
HAVING bool_or(status='started');

工作正常。它对我不起作用的原因是我使用了错误的引号。感谢您的帮助,对于给您带来的不便,我们深表歉意。

having bool_or(status = 'started') 是 Postgres 中的一个不错的选择,并且可能是您在这里的最佳选择。

实际上相当于:

having max( (status = 'started')::int ) = 1

为了完整起见:在标准 SQL 中,您可以用 case 表达式来表达:

having max(case when status = 'started' then 1 end) = 1