如何使用不同的字段获取查询输出

问题描述 投票:-1回答:2
  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
2个回答
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
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.