A | B
=====
1 | 2
3 | 4
2 | 1
如何过滤此表并仅获取唯一的行?这样的事情:
1 | 2
3 | 4
答案 0 :(得分:4)
我想你想要这样的东西:
select a, b
from t
where a <= b
union all
select a, b
from t
where a > b and
not exists (select 1 from t t2 where t2.a = t.b and t2.b = t.a);
注意:这假设您的数据中没有实际的重复项,而您只有一个保留一对,无论顺序如何。
答案 1 :(得分:1)
使用不同的
select distinct least(a,b) as a, greatest(a,b) as b
from the_table;
或者,如果您的DBMS不支持least()
和greatest()
select distinct
case when a < b then a else b end as a,
case when a > b then a else b end as b
from the_table;
答案 2 :(得分:0)
更简单的版本,省略了子查询并通过依靠UNION
来处理实际的重复项:
SELECT a, b FROM test WHERE a <= b
UNION
SELECT b, a FROM test WHERE a > b;