获取 SSMS 中彼此相反的两列的区别

Get the distinct of two columns that are the reverse of each other in SSMS

抱歉,如果这是一个重复的问题,我似乎无法在其他地方找到它。

我有一个 table 像这样:

column1 column2 column3
entry 1 A   B
ENTRY 2 A   C
ENTRY 3 B   C
ENTRY 1 B   A
ENTRY 2 C   A
ENTRY 3 C   B

我使用的 table 有更多列,但思路是一样的。

有没有一种简单干净的方法来获取不同的条目(即我只对带回条目 1 一次感兴趣,而不是两次。

您可以使用 exists 查找重复项,然后使用 <(或 >)获取其中一行;

select t.*
from t
where exists (select 1
              from t t2
              where t2.column1 = t1.column1 and
                    t2.column2 = t1.column3 and
                    t2.column3 = t1.column2
              ) and
      t.column1 < t.column2;
Select distinct t1.Column1, 
  case when t1.Column2 < t2.Column2 then t1.Column2 else t2.Column2 end as Column2,   
  case when t1.Column3 > t2.Column3 then t1.Column3 else t2.Column3 end as Column3  
from myTable t1
inner join myTable t2 on t1.Column1 = t2.Column1 
     and t1.column2 = t2.column3;

编辑:更简单的一个:

Select t1.* 
  from myTable t1
  inner join myTable t2 on t1.Column1 = t2.Column1 
       and t1.Column2 = t2.Column3
  where t1.column2 < t1.column3

EDIT2:如果您还想 return 没有此类欺骗的行:

Select t1.* 
from myTable t1
left join myTable t2 on t1.Column1 = t2.Column1 
   and t1.Column2 = t2.Column3
where t1.column2 < t1.column3 or t2.COlumn1 is null;

如果第 2 列和第 3 列包含您要隐藏的 "reverse duplicates",您必须决定要查看的顺序:

SELECT column1, column2, column3
FROM aTable
WHERE column2 <= column3

根据您的情况,您可以将 distinctouter apply 结合使用。在外部应用中,您可以添加您需要的 order by

select distinct
  t.column1, 
  r.column2,
  r.column3
from myTable t
outer apply (
  select top 1
    r.column2,
    r.column3
  from myTable as r
  where r.column1 = t.column1
) as r

根据您的数据,我假设每个条目具有相同的 column1 值,如果它们是重复的。尝试:

SELECT column1, column2, column3 FROM (
    SELECT column1,
           column2,
           column3,
           ROW_NUMBER() OVER (PARTITION BY column1 ORDER BY column2, column3) rn
    FROM MyTable
) a WHERE rn = 1

到目前为止的所有答案,将丢失单个组合条目的数据。它应该在代码下面

Select distinct t1.Column1, 
  case when t1.Column2 < t1.Column3 then t1.Column2 else t1.Column3 end as Column2,   
  case when t1.Column2 < t1.Column3 then t1.Column3 else t1.Column2 end as Column3  
from myTable t1