简体   繁体   English

如何在PostgreSQL中将结果分组为布尔值

[英]How to group results to boolean value in PostgreSQL

I have a query which returns 我有一个返回的查询

Select bool_val
from .....

The query returns many rows with values of True or False or no rows at all. 查询返回许多行,其值为TrueFalse或根本没有行。

I want the query to ALWAYS return True Or False based on condition that if there is one true the result is True otherwise False . 我希望查询总是返回TrueFalse ,条件是如果有一个为true,则结果为True否则为False

For example: query result: 例如:查询结果:

False
False
True
False

Should return True . 应该返回True

query result: 查询结果:

False
False

Should return False . 应该返回False

query result: 查询结果:

no rows

Should return False since the query is empty. 由于查询为空,应返回False

How can I do that with a query without IFs using PostgreSQL? 如何在没有使用PostgreSQL的IFs情况下执行此操作?

You can use a boolean aggregate: 您可以使用布尔聚合:

select bool_or(bool_val)
from the_table;

To also get a false when the table contains no rows, use coalesce() (thanks Elad) 要在表中不包含任何行时获取false ,请使用coalesce() (感谢Elad)

select coalesce(bool_or(bool_val), false)
from the_table;

Another - possibly faster - option is: 另一个 - 可能更快 - 选项是:

select exists (select 1 from the_table where bool_val)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM