【问题标题】:SQL select distinct "from" and "to" CitiesSQL 选择不同的“来自”和“去”城市
【发布时间】:2021-06-28 23:32:46
【问题描述】:

鉴于下面的旅行表,from_city 和 to_city 有重复的条目。

from_city to_city distance
NYC BOS 300
BOS NYC 300
OKC BOS 600

编写查询以仅检索唯一的组合,如下所示 -

from_city to_city distance
NYC BOS 300
OKC BOS 600

【问题讨论】:

    标签: sql select case distinct


    【解决方案1】:

    假设您没有其他重复项,您可以使用:

    select t.*
    from t
    where t.from_city < t.to_city or
          not exists (select 1
                      from t t2
                      where t2.from_city = t.to_city and
                            t2.to_city = t.from_city
                     );
    

    也就是说,选择按字母顺序排列的行。或者选择反向行不存在的行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 2020-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-18
      相关资源
      最近更新 更多