majidarif
majidarif

Reputation: 20035

mysql group by two columns either way

Is it possible to use group by for two columns where they can be group either way?

Example:

MyTable

Column1 | Column2
      1         2
      2         1
      1         3
      3         1
      3         2
      4         5

Result:

Column1 | Column2
      1         2
      1         3
      3         2
      4         5

As you can see, it groups the 2 columns even though interchanged. but should still get the rows that doesn't have a partner.

Upvotes: 0

Views: 375

Answers (1)

fancyPants
fancyPants

Reputation: 51908

select
least(Column1, Column2),
greatest(Column1, Column2)
from
Table1
group by 
least(Column1, Column2),
greatest(Column1, Column2)
  • see it working live in an sqlfiddle
  • read more about the functions here

Upvotes: 2

Related Questions