如何获取具有不同字段的查询输出

时间:2019-02-04 11:15:28

标签: mysql sql database psql

  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

2 个答案:

答案 0 :(得分: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
                 );

答案 1 :(得分:1)

您可以尝试使用带有group by子句的least()greatest()方法,如下所示。

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