How to find rows where all values of a column are same?

How to find rows where all values of a column are same?

Problem Description:

I have a table user_test_access which stores test_id and user_id.

user_test_access table stores all the uses who have access to the test as well as which user created the test.

idtest_creatortest_iduser_id
101901
201903
302904
402905
503906
613907
703908

I want a query to return all the test_id where there is no creator. i.e test_creator = 0.

Desired Result:

For the particular data set the answer would be test_id 1 and 2.
The reason test_id 3 is not included is because user_id 907 is the test_creator for it.

What I’ve tried:

SELECT test_id from user_test_access WHERE id = ALL(SELECT id from user_test_access WHERE test_creator=0) 

Can you please help me figure out what I’m doing wrong?

Solution – 1

If a missing testcreator is encoded by the value 0, you can just group by the test_id and select only ids where the sum is zero

select test_id 
from user_test_table
group by test_id
having sum(test_creator) = 0

Solution – 2

You can use not exists operator as the following:

SELECT DISTINCT test_id
FROM user_test_access T
WHERE NOT EXISTS (SELECT 1 FROM user_test_access D
  WHERE D.test_id=T.test_id AND D.test_creator=1)

See a demo.

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject