在 Postgresql 中,分组后,如果某列的任何值为 false,则 return false。如果所有值都是true/false,那么分别是returntrue/false

In Postgresql, after grouping, return false if any value of a column is false. If all values are true/false, then return true/false respectively

我有一个名为 'apple' 的 table,我编写了以下查询:

select name, 
       count(name), 
       case when istasty is null then false else istasty end 
from apple 
group by name, istasty; 

这是输出:

我正在尝试使用以下条件对 nameistasty 标志进行分组:

  1. 当对应的name栏既有true也有false,那么我returnfalse。在上图中,talatruefalse istasty 列。但是,我想 return false 因为它至少有一个 false istasty 列。
  2. 如果在对特定名称列的所有 istasty 列进行分组后是 true,则 return true;同样,如果所有 istasty 列都是 false,则该特定名称列的 return false

我可以通过编写查询来实现在 postgresql 中使用 bool_and 运算符:

select name, count(name), bool_and(coalesce(istasty = true, false)) from apple group by name;

有什么方法可以修改我的第一个查询,以便我在 having clause 中添加过滤器以获得与我在第二个查询中使用 bool_and 运算符得到的结果相同的结果?或者还有其他可能的方法吗?

请注意我没有使用 bool_and 运算符。我感谢你的时间。谢谢。

使用 bool_and 运算符的替代方法是常规条件聚合:

SELECT
    name,
    COUNT(*) AS count,
    CASE WHEN SUM(CASE WHEN !istasty THEN 1 ELSE 0 END) > 0
         THEN FALSE ELSE TRUE END AS result
FROM apple
GROUP BY name;

当您建议使用 HAVING 子句时,我不确定您的想法是什么。通过将条件检查移至 HAVING 子句,您可以 exclude/include 查询中匹配条件的特定组。

您的逻辑(return 仅当所有值都为真时才为真)等同于获取 min() 布尔值:

select
    name,
    min(istasty::varchar(5))::boolean
from (select name, case when istasty is null then false else istasty end istasty
      from apple
      group by name, istasty) x
group by name

请注意,postgres 不支持聚合 boolean 值,因此您必须转换为字符,然后返回布尔值才能使用 min()