I have a table like below:
city1 | city2 | dist |
---|---|---|
New York | Berlin | 7900 |
Berlin | New York | 7900 |
Oregon | Ohio | 5700 |
Montreal | Rio | 5700 |
Ohio | Oregon | 5700 |
Rio | Montreal | 5700 |
Moscow | Tokyo | 4200 |
Tokyo | Moscow | 4200 |
Both row 1 and row 2 are same things and the only difference is in the first one Berlin is city2 and in the second one Berlin is city1.
I want to show this kind of rows only once…
How to do it?
4
Answers
You can do:
I added a couple of unmatched edge cases in the demo fiddle.
Use a CASE statement to ensure that the smaller of the two city names always appears first.I mean, "a" is minimal and Z is maximal.s minimal and Z is maximal. This way, each pair will have a unique representation.
Then,group the data by the newly ordered city pairs and then filter out duplicates.
You can self LEFT JOIN and see if any matches are there
Depending on th last OR condition you can choose which cite are shown in the result set
fiddle
Here’s the simplest query that works:
The joins are unnecessary.