gpt4 book ai didi

sql - Postgresql 删除重复的反向对

转载 作者:行者123 更新时间:2023-11-29 14:30:19 25 4
gpt4 key购买 nike

我有这张表:

 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但它对我没有用,因为我有字符串归档。

谢谢

最佳答案

一种方法使用聚合:

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);

关于sql - Postgresql 删除重复的反向对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52871795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com