How to remove opposite rows from a SQL table

I have the following SQL table:

A|B
---
w|x
x|w
y|z
z|y

Is it possible to build a query that will give the following result:

A|B
---
w|x
y|z

To summarize, I would like to consider two columns as an unordered set, such that (a, b) == (b, a).

+3
source share
2 answers

The "best" code is database dependent, but the following is dbms-agnostic:

SELECT      t.A,
            t.B
FROM        my_table t
LEFT JOIN   my_table t2
        ON  t.A = t2.B
        AND t.B = t2.A
        AND t.A < t.B
WHERE       t2.A IS NULL
+2
source

You can try the following:

SELECT LEAST(a,b) a, GREATEST(a,b) b
FROM t
GROUP BY LEAST(a,b), GREATEST(a,b)

With the following test pattern t:

CREATE TABLE t ( a VARCHAR(1), b VARCHAR(1) );

INSERT INTO t VALUES ('w','x'),('x','w'),('y','z'),('z','y');

it returns:

w  x
y  z

Using LEASTand GREATEST, also be sure to w xreturn instead x w.

+1
source

Source: https://habr.com/ru/post/1734748/


All Articles