Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PostgreSQL select unique rows based on any combinations of 2 cols

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

SELECT t1.*
FROM t t1
LEFT JOIN t t2 ON t1.city1 = t2.city2 and t2.city2 = t1.city1 AND t1.dist = t2.dist
WHERE t2.city1 IS NULL 
  OR t1.city1 > t1.city2
city1 city2 dist
Conce Santiago 500
New York Berlin 7900
Oregon Ohio 5700
Rio Montreal 5700
Talca Linares 80
Tokyo Moscow 4200
SELECT 6
SELECT t1.*
FROM t t1
LEFT JOIN t t2 ON t1.city1 = t2.city2 and t2.city2 = t1.city1 AND t1.dist = t2.dist
WHERE t2.city1 IS NULL 
  OR t2.city1 > t2.city2
city1 city2 dist
Berlin New York 7900
Conce Santiago 500
Montreal Rio 5700
Moscow Tokyo 4200
Ohio Oregon 5700
Talca Linares 80
SELECT 6

fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading