Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to exclude all rows where a column value is different but other columns are the same

So many similar questions – mainly the questions are about how to select one of the duplicates where only a single column is different, but I want to exclude all of them from a query, and only get the ones where a particular field isn’t different.

I am looking for all the reference_no where the status is -1, except for those where the status is both -1 and 1 for the same reference_no, as in the table below. The query should return only row Id 4. How do I do that?

This is using SQL server 2016

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

| id  | process_date | status | reference_no |
| --- | ------------ | ------ | -----------  |
| 1   | 12/5/22      | 1      | 789456       |
| 2   | 12/5/22      | -1     | 789456       |
| 3   | 12/5/22      | 1      | 789456       |
| 4   | 12/5/22      | 1      | 321654       |

>Solution :

If I understand correctly you want a not exists check

select *
from t
where status = -1 
and not exists (
  select * from t t2 
  where t2.status = 1 and t2.reference_no = t.reference_no
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading