【问题标题】:SQL: Retrieve Distinct for different columnsSQL:检索不同列的不同
【发布时间】:2020-02-13 10:49:45
【问题描述】:

我有以下场景:

在 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|
|----------------------------------------|-------------------------------------|

谢谢

【问题讨论】:

    标签: sql sql-server distinct distinct-values


    【解决方案1】:

    一个简单的方法是:

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-03
      • 1970-01-01
      • 2018-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多