2

我有一个包含五个布尔列的表。

如何构造一个返回至少 2 列为真的行的查询?

4

3 回答 3

8

将布尔类型转换为整数 ( 0=false, 1=true) 并检查它们的总和:

select *
from my_table
where a::int + b::int + c::int + d::int + e::int >= 2;
于 2013-04-26T23:33:44.887 回答
2

漫长的道路:

SELECT * from t where c1 and c2 or c1 and c3 or c1 and c4 or c1 and c5
or c2 and c3 or c2 and c4 or c2 and c5 or c3 and c4 or c3 and c5 or c4 and c5;
于 2013-04-26T23:26:12.063 回答
1

接受的答案仅在所有列都已定义NOT NULL(未指定)的情况下才有效。为了使它也可以与 一起使用NULL

SELECT *
FROM   tbl
WHERE (a IS TRUE)::int
    + (b IS TRUE)::int
    + (c IS TRUE)::int
    + (d IS TRUE)::int
    + (e IS TRUE)::int > 1;

或者:

SELECT *
FROM   tbl
WHERE  COALESCE(a::int, 0)
     + COALESCE(b::int, 0)
     + COALESCE(c::int, 0)
     + COALESCE(d::int, 0)
     + COALESCE(e::int, 0) > 1;
于 2014-05-28T02:57:55.503 回答