I have a table as given below.
Fare | City1 | City2 | Dist |
---|---|---|---|
100 | A | B | 10 |
100 | B | A | 10 |
200 | A | C | 20 |
150 | B | D | 15 |
150 | D | B | 15 |
I want to select all records with a distinct combination of City1 and City2. Please note that A,B and B,A should be considered as same combination.
The desired output is as follows.
Fare | City1 | City2 | Dist |
---|---|---|---|
100 | A | B | 10 |
200 | A | C | 20 |
150 | B | D | 15 |
Thank you!
3
Answers
Based on your sample data with two combinations of each possible you could try
My original answer to this was too convoluted so I’ve removed it. See MatBaille’s query to give the correct answer with neat SQL provided there is no ‘bad data’. This question is a good advertisement for working with normalised data because there are too many alternative ways to handle ‘bad data’.
To check for bad data, where Fare or Dist are different on different rows for the same unordered pair of cities, this shouldn’t return any rows.
If it does, then the application reading from the SELECT DISTINCT… query will have to decide how to handle multiple rows with the same pair of cities.
Force the order to always be the same, then select only the distinct rows.
Having noted the other answers, MySQL includes LEAST() and GREATEST(), allowing tidier code…