【问题标题】:Postgresql remove duplicate reversed pairsPostgresql 删除重复的反向对
【发布时间】:2018-10-18 10:15:36
【问题描述】:

我有这张桌子:

 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 但这对我没有用,因为我已经提交了字符串。

谢谢

【问题讨论】:

    标签: sql postgresql pgrouting


    【解决方案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);
    

    【讨论】:

      【解决方案2】:

      row_numbercount 的一个选项使用 leastgreatest

      select origin,dest,case when cnt_per_pair=1 then 1 else 0 end as one_way
      from (select t.*,row_number() over(partition by least(origin,dest),greatest(origin,dest) 
                                         order by dest) as rnum,
            count(*) over(partition by least(origin,dest),greatest(origin,dest)) as cnt_per_pair
            from tbl t
           ) t
      where rnum=1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-02-17
        • 2014-05-10
        • 1970-01-01
        • 2021-12-16
        • 2020-08-17
        • 1970-01-01
        • 2022-11-02
        相关资源
        最近更新 更多