HI有3个产品表,每个表有3列,分别是customer name、boolean optout和blacklist。Having子句之后,每个客户名称将有3行(假设他拥有所有3个产品)。
如果任何布尔列包含true,如何输出true。我用下面的cast操作解决了这个问题,但是我认为应该有一个更优雅的解决方案。

SELECT customer_name,
       cast(int4(sum(cast(optout     As int4))) As Boolean) As optout,
       cast(int4(sum(cast(blacklist  As int4))) As Boolean) As blacklist
FROM
(SELECT * FROM product1
UNION SELECT * FROM product2
UNION SELECT * FROM product3) AS temp1
GROUP BY customer_name, optout, blacklist
HAVING optout=true or blacklist=true;

最佳答案

尝试bool_or聚合函数,听起来就像您正在寻找的:

SELECT customer_name,
       bool_or(optout)    As optout,
       bool_or(blacklist) As blacklist
FROM
(SELECT * FROM product1
UNION SELECT * FROM product2
UNION SELECT * FROM product3) AS temp1
GROUP BY customer_name, optout, blacklist
HAVING optout=true or blacklist=true;

关于postgresql - sql:如何在HAVING子句之后从一列 bool 值中选择具有真值的行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5700269/

10-12 14:15