Sql - query multiple lines

I have a table with names and a bit column indicating if the name is delted (1) or not (0). I am trying to write a query that returns all deleted names, unless the name is also deleted (the name can appear more than once in the table). Hope this makes sense!

Here are some sample data:

+------+-------+
|Name  |Deleted|
+------+-------+
|Bob   |   1   |
+------+-------+
|Joe   |   1   |
+------+-------+
|Joe   |   0   |
+------+-------+
|Bob   |   1   |
+------+-------+
|Sam   |   1   |
+------+-------+

      

So the result will be Bob

and Sam

:
Both records "Bob" are "1".
Single entry Sam - 1.

Joe would not be in the results because he is both "1" and "0".

Thanks for any help!

+3


source to share


2 answers


One method uses aggregation:



select name
from t
group by name
having min(deleted) = 1;

      

+3


source


SELECT T.Name
  FROM Table T
 WHERE T.Deleted = 1
   AND NOT EXISTS (SELECT *
                     FROM Table T2
                    WHERE T2.Name = T.Name
                      AND T2.Deleted = 0)

      



+1


source







All Articles