I have data in which i have duplicates but in different columns for ex :
Column A | Column B |
---|---|
1 | 2 |
2 | 1 |
3 | 4 |
4 | 3 |
but now my output should look like
Column A | Column B |
---|---|
1 | 2 |
3 | 4 |
how can i achieve this using sql query ?
CodePudding user response:
We can use a least/greatest trick here:
SELECT DISTINCT LEAST(a, b) AS a, GREATEST(a, b) AS b
FROM yourTable;
The idea is to, e.g., take the two tuples (1, 2)
and (2, 1)
and bring them both to (1, 2)
, using the LEAST()
and GREATEST()
functions. Then, we just retain one them using DISTINCT
.