简体   繁体   中英

SQL unique combination of two columns

Hi I'm stumped as to this problem as I need a unique combination of two instances of the same column.

Let's say I have a table Animal with a column Name. I want all "unique" combinations of the animal name and not a repeat of it self or another already existing row.

Sample data:

Name
-------
Mouse
Cat
Dog

The result I want is:

Name1   Name2
-----   -----
Mouse   Cat
Mouse   Dog
Cat     Dog

I wrote the following query:

SELECT DISTINCT A1.name AS Name1, A2.name as Name2
FROM Animal A1, Animal A2
WHERE A1.name <> A2.name;

Which netted me the following results instead:

Name1  Name2
-----  -----
Mouse  Cat
Mouse  Dog
Cat    Mouse
Cat    Dog
Dog    Mouse
Dog    Cat

I hope I'm making sense. I don't want a duplicate of both combination, whether it appears on the left or on the right. As far as "Distinct" is concern the rows are distinct. So is there some way to eliminate the double up?

To find unique combinations, just change <> to < :

WHERE A1.name < A2.name;
             ^^^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM