Given two columns (Animal and Name) how do I write a SQL statement that finds the rows that don’t have a 1 to 1 relationship i.e. Dog = Patch and Dog = Rover ?
| Animal | Name |
|---|---|
| Dog | Patch |
| Cat | Sylvester |
| Mouse | Gerry |
| Mouse | Gerry |
| Dog | Rover |
>Solution :
You may EXISTS operator with a correlated subquery as the following:
SELECT Animal, Name
FROM table_name T
WHERE EXISTS(SELECT 1 FROM table_name D WHERE D.Animal=T.Animal AND D.Name<>T.Name)
ORDER BY Animal
See a demo.