简体   繁体   中英

Query to return (grouped) rows where no row with column=condition exists

Let's say I have a table with two columns, a client_id and a boolean.

There are multiple data entries for a given client_id, each of which may or may not have the boolean value set to true.

I need a query that will return only the client_ids that have NO ROWS with the boolean set to true, and I need it grouped by client_id.

I'm sure this is simple, it just escapes me right now.

Use the HAVING clause to filter the groups:

SELECT client_id FROM my_table GROUP BY client_id HAVING SUM(boolean) = 0

Note that SUM(boolean) works in MySQL because it does not have true boolean types; in other RDBMS you would either have to use a different aggregate function or else test the boolean and return a result that can be used in SUM() :

... HAVING SUM(CASE WHEN boolean THEN 1 END) = 0

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