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

SQL to fetch value of one column such that a certain value in another column does not exist

I have the following Table t

key value
1 a
1 b
1 c
2 a
2 c

In the above table, the Key 1 has three values i.e. a, b and c. However Key 2 has only two values i.e. a and c.

How to write a SQL that would return the Key that does NOT have the value ‘b’? In the above example the SQL must return the Key 2

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

>Solution :

You could do it like this by creating a counter for b values per key and then selecting only the keys with 0 b values:

SELECT 
   key
FROM (SELECT
         t.key, 
         SUM(CASE WHEN t.value = 'b' THEN 1 ELSE 0 END) AS number_of_b_values
      FROM t
      GROUP BY t.key)
WHERE number_of_b_values = 0
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