删除包含两列可能包含相同数据的行

时间:2017-12-20 13:59:25

标签: sql sql-server tsql

以下面的数据为例,

Letter One | Letter Two    
         A | B
         B | A
         A | C

我怎样才能选择任何具有相同数据的行,所以在这种情况下我希望输出删除第二行,因为这两个字母是相同的。 所以我的输出是:

Letter One | Letter Two
         A | B 
         A | C

3 个答案:

答案 0 :(得分:1)

假设没有确切的重复,你可以这样做:

select letterA, letterB
from t
where letterA <= letterB
union all
select letterA, letterB
from t
where letterA > letterB and
      not exists (select 1 from t t2 where t2.letterA = t.letterB and t2.letterB = t.letterA);

如果您不关心最终列的顺序,可以执行以下操作:

select distinct (case when letterA <= letterB then letterA else letterB end) as letterA,
       (case when letterA > letterB then letterA else letterB end) as letterB
from t;

答案 1 :(得分:1)

SELECT 
         l1.LetterOne , l1.LetterTwo
FROM
         letters l1
LEFT JOIN
         letters l2 ON l1.LetterOne = l2.LetterTwo AND l1.LetterTwo = l2.LetterOne
WHERE
         l2.LetterOne IS NULL OR l1.LetterOne < l2.LetterOne

答案 2 :(得分:1)

UNION将过滤掉重复项。 最低值将在第一列中返回:

SELECT LetterOne, LetterTwo
FROM <table>
WHERE LetterOne < LetterTwo
UNION 
SELECT LetterTwo, LetterOne
FROM <table>
WHERE LetterTwo<=LetterOne