tags:

views:

584

answers:

1

Hi!

Recently I came across with the following quiz. Imagine we have this table

+--------+
| colors |
+--------+
| red    |
| black  |
| white  |
| green  |
| orange |
+--------+

The task is to write a SQL query that will select all pairs without allowing duplicates. Permutations are counted too ({red, black} = {black, red}, hence only one of the pair is allowed).

+23  A: 

Try this

Select A.Color, B.Color
From Colors A
Cross Join Colors B
Where A.Color > B.Color
Charles Bretana
+1 - I am slow
John Rasch
+1 fastest and enlightened :)
Roee Adler
Black = Black would be false, therefore it wouldt get selected. The above query looks good to me
Neil N
@I'm slow too. *deleting...*
Raj More
Here is an interesting link on CROSS JOINShttp://www.databasejournal.com/sqletc/article.php/1438121/Generate-Test-Data-Quickly-with-Cross-Joins.htm
Cody C
Damn, you good. And why it is working? :)
glaz666
@glaz, because a cross join means take every element in Set A and pair it with every element in Set B... So you get every possible ordered combination. The Where clause predicate just eliminates the ones where the element pairs are from the same element, and one of the duplicates... (A, B) and (B, A)
Charles Bretana