Sql 将两列与同一表进行比较以删除重复项

Sql 将两列与同一表进行比较以删除重复项,sql,informatica,Sql,Informatica,一个有两列的示例表,我需要将第1列和第2列与相同的表记录进行比较,并需要删除第1列+第2列=第2列+第1列 我试着做自连接和case条件。但是它不起作用下面的SQL将得到相反的col1和col2行: select distinct t2.col1,t1.col2 from table t1 join table t2 on t1.col1 = t2.col2 and t1.col2 = t2.col1 当我们得到这些反向行时,我们可以使用left join子句将它们除去

一个有两列的示例表,我需要将第1列和第2列与相同的表记录进行比较,并需要删除第1列+第2列=第2列+第1列


我试着做自连接和case条件。但是它不起作用

下面的SQL将得到相反的col1和col2行:

select
    distinct t2.col1,t1.col2
from
    table t1
join
    table t2 on t1.col1 = t2.col2 and t1.col2 = t2.col1
当我们得到这些反向行时,我们可以使用left join子句将它们除去,完整的SQL是:

select
    t.col1,t.col2
from
    table t
left join
    (
      select
        distinct t2.col1,t1.col2
      from
        table t1
      join
        table t2 on t1.col1 = t2.col2 and t1.col2 = t2.col1
    ) tmp on t.col1 = tmp.col1 and t.col2 = tmp.col2
where
    tmp.col1 is null

清楚吗?

好的。可能有一种更简单的方法,但也可以。{table}将替换为您的表名

;with orderedtable as (select t1.col1, t1.col2, ROW_NUMBER() OVER(ORDER BY t1.col1, t1.col2 ASC) AS rownum
from (select distinct t2.col1, t2.col2 from {table} t2) as t1)

select f1.col1, f1.col2
from orderedtable f1
left join orderedtable f2 on f1.col1 = f2.col2 and f1.col2 = f2.col1 and f1.rownum < f2.rownum
where f2.rownum is null
您可以使用运算符

Exception从左输入查询返回右输入查询未输出的不同行


给定数据集的示例:

如果我理解正确,如果表中有所有反向对,您可以像这样运行一个简单的select:

select col1, col2
from t
where col1 < col2;
如果您有一些单身人士,那么:

select col1, col2
from t
where col1 < col2 or
      (col1 > col2 and
       not exists (select 1
                   from t t2
                   where t2.col1 = t.col2 and
                         t2.col2 = t.col1
                  )
      );

我发布的答案基于oracle数据库,列为string/varchar:

从rowid所在的表中删除 从表中选择rowid 其中column1 | | column2=column2 | | column1


请随意提供更多输入,我们可以调整答案。

您尝试了什么查询?您的RDBMS是什么?MySQL、SQL Server、Oracle……我想我已经解决了这个问题,但为什么会得到负面分数?如果它不工作或抛出错误,请告诉我。或者您希望得到不同的输出
select col1, col2
from t
where col1 < col2 or
      (col1 > col2 and
       not exists (select 1
                   from t t2
                   where t2.col1 = t.col2 and
                         t2.col2 = t.col1
                  )
      );