[英]Only return rows if all items with the same ID has all the same value in another column
[英]Returning rows with the same id and separate column all containing same value
order_id | fulfilled
---------------------
166 | true
166 | true
167 | true
167 | false
167 | false
168 | true
我试图只选择具有相同 order_id 的所有行也都fulfilled
的 id。
在上面的示例中,我只想返回 order_ids 166、168。因为与这些 id 匹配的所有行都已满足。
167 不符合标准,因为其中一些是错误的。
完成此 PostgreSQL 的最佳方法是什么?
我试过例如:
select
order_id, fulfilled
from orders_orderround
where fulfilled = true
order by order_id`
不起作用,因为它正在返回任何满足 true 的记录。 我尝试使用HAVING
但仍然有问题。
如果您只想要一个所有记录都得到满足的订单 ID 列表,您可以使用带有having
子句的聚合和过滤器:
select order_id
from orders_orderround
group by order_id
having bool_and(fulfilled)
bool_and()
是一个方便的 Postgres 聚合函数,如果所有输入值都为真,则返回true ,否则返回 false 。
只需获取不包含 fullfill at false 的行的 id
select order_id
from orders_orderround a
where not exists
(
select 1 from orders_orderround b
where a.order_id = b.order_id and fulfilled = false
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.