简体   繁体   中英

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

I'm trying to only select the ids where all of the rows that have the same order_id also have fulfilled true.

In the example above I would only want returned the order_ids 166, 168. Since all of the rows that match those ids have fulfilled true.

167 does not meet the criteria since some of them are false.

What is the best way to accomplish this PostgreSQL?

I tried for example:

select 
order_id, fulfilled
from orders_orderround
where fulfilled = true
order by order_id`

Does not work since it is returning any record that has fulfilled true. I tried using HAVING but still having an issue.

If you just want a list of order ids whose all records are fulfilled, you can use aggregation and filter with a having clause:

select order_id
from orders_orderround
group by order_id
having bool_and(fulfilled)

bool_and() is a handy Postgres aggregate function that returns true if all input values are true, otherwise false .

Just get the ids without a row containing a fullfilled at false

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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