Sql server 从SQL中删除重复元组

Sql server 从SQL中删除重复元组,sql-server,tsql,Sql Server,Tsql,我有一个SQL Server表,如下所示: | a | b | +---+---+ | 1 | 2 | | 2 | 1 | | 3 | 4 | | 4 | 3 |, etc... 我想删除所有第二对以获得以下结果 | a | b | +---+---+ | 1 | 2 | | 3 | 4 |, etc... 一个简单的方法是: select a, b from t where a < b; 这假定表示所有对 如果不是,则可以扩展此功能: select a, b from t wher

我有一个SQL Server表,如下所示:

| a | b |
+---+---+
| 1 | 2 |
| 2 | 1 |
| 3 | 4 |
| 4 | 3 |, etc...
我想删除所有第二对以获得以下结果

| a | b |
+---+---+
| 1 | 2 |
| 3 | 4 |, etc...
一个简单的方法是:

select a, b
from t
where a < b;
这假定表示所有对

如果不是,则可以扩展此功能:

select a, b
from t
where a < b or
      (b < a and
       not exists (select 1 from t t2 where t2.a = t.b and t2.b = t.a)
      );
这将保留ab的所有行(如果没有a和b值切换的对应行)。

一个简单的方法是:

select a, b
from t
where a < b;
 SELECT DISTINCT CASE WHEN a < b THEN a ELSE b END as a,
                 CASE WHEN a < b THEN b ELSE a END as b
 FROM yourTable
这假定表示所有对

如果不是,则可以扩展此功能:

select a, b
from t
where a < b or
      (b < a and
       not exists (select 1 from t t2 where t2.a = t.b and t2.b = t.a)
      );
这将保留ab的所有行,前提是并没有切换a和b值的对应行

 SELECT DISTINCT CASE WHEN a < b THEN a ELSE b END as a,
                 CASE WHEN a < b THEN b ELSE a END as b
 FROM yourTable
这里,如果你有1,2和2,1,你以1,2结束

但是如果你只有2,1,也以1,2结尾

这里,如果你有1,2和2,1,你以1,2结束

但是,如果只有2,1,也以1,2结尾,并带有自联接:

select distinct t.*
from tablename t left join tablename tt
on tt.a = t.b and tt.b = t.a
where tt.a is null or t.a <= t.b
使用自联接:

select distinct t.*
from tablename t left join tablename tt
on tt.a = t.b and tt.b = t.a
where tt.a is null or t.a <= t.b

您的数据不清楚:您是否可以有一个记录,例如a=6,b=5,但没有相应的a=5,b=6,在这种情况下,a=6,b=5将包含在您的结果集中?也就是说,您想要的是没有所有排列的值的组合?是要从表中删除重复项,还是只选择不同的组合?这是两个不同的东西…您的数据不清楚:您是否可以有一个记录,例如a=6,b=5,但没有相应的a=5,b=6,在这种情况下,a=6,b=5将包含在您的结果集中?也就是说,您想要的是没有所有排列的值的组合?是要从表中删除重复项,还是只选择不同的组合?这是两个不同的东西…请解释你的b