9

Possible Duplicate:
combinations (not permutations) from cross join in sql

I've currently got a table with the following records:

A1
A2
A3
B1
B2
C1
C2

Where the same letter denotes some criteria in common (e.g. a common value for the column 'letter'). I do a self join on the criteria as follows:

SELECT mytable.*, self.* FROM mytable INNER JOIN mytable AS self 
   ON (mytable.letter = self.letter and mytable.number != self.number);

This join gives something like the following:

A1 A2
A2 A1
A1 A3
A3 A1
A2 A3
A3 A2
B1 B2
B2 B1
C1 C2
C2 C1

However, I only want to include each pair once (a combination instead of a permutation). How would I get the following:

A1 A2
A1 A3
A2 A3
B1 B2
C1 C2
Community
  • 1
  • 1
EoghanM
  • 25,161
  • 23
  • 90
  • 123

1 Answers1

19

Changing the JOIN condition slightly will achieve what you want..

Instead of:

ON (mytable.letter = self.letter and mytable.number != self.number)

use

ON (mytable.letter = self.letter and mytable.number > self.number)

This will only include combinations where self.number is greater than mytable.number which in effect restricts the results to one valid ordering of each combination...

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Phill_P
  • 399
  • 2
  • 6