gpt4 book ai didi

sql - HiveQL:如何删除基于两列的重复行

转载 作者:可可西里 更新时间:2023-11-01 15:07:56 29 4
gpt4 key购买 nike

我正在创建一个无向图表,如下所示。

+-------------------+------------------------+----------------------+
| id | node_a | node_b |
+-------------------+------------------------+----------------------+
| 1 | a | b |
+-------------------+------------------------+----------------------+
| 2 | a | c |
+-------------------+------------------------+----------------------+
| 3 | a | d |
+-------------------+------------------------+----------------------+
| 4 | b | a |
+-------------------+------------------------+----------------------+
| 5 | b | c |
+-------------------+------------------------+----------------------+
...

行id=1 和id=4 是重复的行,应该删除一个。删除此表中所有重复行的有效方法是什么?

最佳答案

您可以通过执行以下操作生成不同的行:

select e.*
from edges e
where e.node_a < e.node_b
union all
select e.*
from edges e
where e.node_a > e.node_b and
not exists (select 1
from edges e2
where e2.node_a = e.node_b and e2.node_b = e.node_a
);

如果您确实有未转置的重复项,请使用 union 而不是 union all

上面保留了表格中的原始边缘。如果这不是问题,一个简单的方法是:

select distinct least(node_a, node_b) as node_a, greatest(node_a, node_b) as node_b
from edges e;

关于sql - HiveQL:如何删除基于两列的重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57501665/

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