SQL仅获得两列的唯一组合

时间:2018-11-09 21:31:28

标签: sql sql-server combinations

我的桌子有:

A     B
1     2
2     1

并且我尝试使用sql命令获得仅一种组合

A     B
1     2

我该怎么做?

1 个答案:

答案 0 :(得分:2)

标准SQL中的一种规范方法是:

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);

请注意,这假定没有重复或相等的值。您可以使用select distinct<=比较轻松地处理这些问题。以我的经验,每对最多有两行时,经常会出现此问题。

这将保留原始值。因此,如果您从以下内容开始:

1    2
5    4

您将在结果集中得到它。

如果您不关心订购,那么许多数据库都支持least() / greatest()

select least(a, b) as a, greatest(a, b) as b
from t
group by least(a, b), greatest(a, b);

您可以使用case表达式执行相同的操作。或者,更简单地说是:

select distinct least(a, b) as a, greatest(a, b) as b
from t;
相关问题