简体   繁体   中英

How to exclude all rows with the same ID based on one record's value in psql?

在此处输入图片说明

Say I have the results above, and want to exclude all rows with ID of 14010497 because at least one of the rows has a date of 2/25. How would I filter it down? Using a WHERE table.end_date > '2019-02-25' would still include the row with a date of 2-23

Try something like this:

  select * from your_table
  where id not in (
     select distinct id
     from your_table
     where end_date > '2019-02-25'
     )
  /

I would use not exists :

select t.*
from t
where not exists (select 1
                  from t t2
                  where t2.id = t.id and t2.end_date = '2019-02-25'
                 );

I strongly advise using not exists over not in because it handles NULL values much more intuitively. NOT IN will return no rows at all if any value in the subquery is NULL .

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