PostgreSQL删除重复的反向对

时间:2018-10-18 10:15:37

标签: sql postgresql pgrouting

我有这张桌子:

 origin     destination

new york      seattle
new york      chicago
new york      portland
seattle       new york
seattle       chicago
chicago       new york

我必须建立一个图,所以我需要删除所有重复的反向对,以使它们具有:

origin      destination oneway

new york      seattle     0
new york      chicago     0
new york      portland    1
seattle       chicago     1

我已经阅读了这篇文章: SQL -- Remove duplicate pairs 但这对我没有用,因为我已经提交了字符串。

谢谢

2 个答案:

答案 0 :(得分:1)

一种方法使用聚合:

select origin, destination,
       (case when exists (select 1
                          from t t2
                          where t2.origin = t.destination and t2.destination = t.origin
                         )
             then 0 else 1
        end) as one_way
from t
where origin < destination
union all
select origin, destination, 1
from t
where origin > destination;

另一种使用窗口函数的方法:

select origin, destination, (cnt = 1)::int as one_way
from (select t.*,
             count(*) over (partition by least(origin, destination), greatest(origin, destination)) as cnt
      from t
     ) t
where origin < destination or
      (origin > destination and cnt = 1);

答案 1 :(得分:1)

使用leftViewrow_numbercountleast的一个选项。

greatest