Consider the below Table structure and data
CREATE TABLE Distance(
source VARCHAR(20),
destination VARCHAR(20),
distance INTEGER
);
Select * from Distance;
source destination distance
======= =========== ======
Chennai Mumbai 500
Mumbai Chennai 500
Mumbai Bangalore 500
Bangalore Mumbai 500
Goa Mumbai 100
Mumbai Goa 100
Kolkata Goa 1000
I need the output to have single record for 2 cities if repeating, i,e, any one record among the below 2 is fine.
Chennai Mumbai 500
Mumbai Chennai 500
Expected o/p:
source destination distance
======= =========== ======
Chennai Mumbai 500
Mumbai Bangalore 500
Goa Mumbai 100
Kolkata Goa 1000
If you need to preserve the order of columns you might use
When multiple rows per
source/combination
exist you must either addDISTINCT
or aGROUP BY
.Here is one method using
least()
andgreatest()
:This has the disadvantage that you could return a row not in the table. For instance, if you had a single row with "Mumbai/Chennai/500", then this query would return "Chennai/Mumbai/500" -- and this row is not in the original table.
So, an alternative method is:
This version is also ANSI-compatible and should work in all databases.