SQL:检索不同列的唯一性

问题描述 投票:0回答:1

我有以下情况:

在SQL表中,我具有以下列:

|----------------------------------------|-------------------------------------|
|      Col 1                             |     Col 2                           |
|----------------------------------------|-------------------------------------|
| 4BAEFCAD-0B61-E911-B26B-005056872FC1   | 855757A6-0D61-E911-B26B-005056872FC1|
|----------------------------------------|-------------------------------------|
| 855757A6-0D61-E911-B26B-005056872FC1   | 4BAEFCAD-0B61-E911-B26B-005056872FC1|
|----------------------------------------|-------------------------------------| 
| D2ADDEF8-A3A8-E911-B272-005056872FC1   | CED9DFD0-35A9-E911-B272-005056872FC1|
|----------------------------------------|-------------------------------------|

前两行是对相同记录的引用,因为它们在第1行和第2行中包含相同的值,但是被交换了。

是否只有一个SQL方式检索这两个列之一?这样最终我会收到以下结果:

|----------------------------------------|-------------------------------------|
|      Col 1                             |     Col 2                           |
|----------------------------------------|-------------------------------------|
| 4BAEFCAD-0B61-E911-B26B-005056872FC1   | 855757A6-0D61-E911-B26B-005056872FC1|
|----------------------------------------|-------------------------------------| 
| D2ADDEF8-A3A8-E911-B272-005056872FC1   | CED9DFD0-35A9-E911-B272-005056872FC1|
|----------------------------------------|-------------------------------------|

THX

sql sql-server distinct distinct-values
1个回答
2
投票

一个简单的方法是:

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

这具有保留原始行的优点。如果您不关心订购:

select distinct (case when col1 < col2 then col1 else col2 end) as col1,
       (case when col1 < col2 then col2 else col1 end) as col2
from t;
© www.soinside.com 2019 - 2024. All rights reserved.