如何删除oracle中的逻辑重复项

时间:2016-11-22 18:59:24

标签: sql oracle

我们如何从下表中删除逻辑重复项(即当from和to是相同的站点时,应该返回2行)

 from_station| to _station| distance  
 delhi   |      mumbai   |   5000  
 mumbai  |      delhi    |  5000  
 delhi   |      cochin   |   3000  
 cochin  |      delhi    |   3000  

提前致谢

2 个答案:

答案 0 :(得分:2)

select   distinct

         least    (from_station,to_station)
        ,greatest (from_station,to_station)
        ,distance 

from     t

答案 1 :(得分:1)

如果您只想返回结果,那么您可以执行以下操作:

select t.*
from t
where t.from_station < t.to_station
union all
select t.*
from t
where t.from_station > t.to_station and
      not exists (select 1
                  from t t2
                  where t2.from_station = t.to_station and t2.to_station = t.from_station
                 );

另一种机制使用聚合:

select least(t.from_station, t. _station) as from_station,
       greatest(t.from_station, t. _station) as to_station,
       avg(distance)
from t
group by least(t.from_station, t. _station),
         greatest(t.from_station, t. _station);

但是,这可能会引入不在原始数据中的行(如果两个城市对之间只存在一行)。