【问题标题】:How to get Query output with distinct fields如何获取具有不同字段的查询输出
【发布时间】:2019-02-04 11:15:28
【问题描述】:
  source   | destination | totalkms >
-----------+-------------+----------
 chennai   | bangalore   |      400
 bangalore | chennai     |      400
 mumbai    | delhi       |     1400
 delhi     | mumbai      |     1400
 delhi     | patna       |      800

预期输出是

  source   | destination | totalkms 
  ---------+-------------+----------
 chennai   | bangalore   |      400
 mumbai    | delhi       |     1400
 delhi     | patna       |      800

【问题讨论】:

    标签: mysql sql database psql


    【解决方案1】:

    您可以使用not existsunion all

    select t.*
    from t
    where t.source < t.destination
    union all
    select t.*
    from t
    where t.source > t.destination and
          not exists (select 1
                      from t t2
                      where t2.source = t.destination and t2.destination = t.source and
                            t2.totalkms = t.totalkms
                     );
    

    【讨论】:

      【解决方案2】:

      您可以尝试least()greatest() 方法以及下面的group by 子句。

      select least(source, destination),greatest(source, destination),max(totalkms) from test_travel group by least(source, destination),greatest(source, destination);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-11
        相关资源
        最近更新 更多