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
你可以使用not exists
和union 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
);
您可以使用group by子句尝试least()和greatest()方法,如下所示。
select least(source, destination),greatest(source, destination),max(totalkms) from test_travel group by least(source, destination),greatest(source, destination);