在SSMS中获取彼此相反的两列

时间:2018-07-25 12:01:00

标签: sql sql-server tsql ssms distinct

很抱歉,如果这是一个重复的问题,我似乎在其他任何地方都找不到。

我有一张像这样的桌子:

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

我正在使用的表具有更多列,但想法是相同的。

是否有一种简单的干净方法来获取不同的条目(即,我只想将条目1取回一次,而不是两次。

6 个答案:

答案 0 :(得分:4)

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:如果您还想返回没有此类重复项的行:

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;

答案 1 :(得分: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;

答案 2 :(得分:1)

如果第2列和第3列包含要隐藏的“反向重复项”,则必须决定要查看的顺序:

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

答案 3 :(得分:1)

根据您的数据,我假设每个重复项都具有相同的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

答案 4 :(得分:0)

如果您遇到这种情况,可以将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

答案 5 :(得分:0)

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

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