如何解决使用 SQL 将后续行中的反向对组合在一起
我正在处理超过 500,000 行的数据集,其中包含 Parent 和 Child(同一个家庭)的 ID。
但是,数据集中存在 ID 颠倒(从而导致循环)的一些问题。
我能够提取有问题的记录(大约 2000 行),但我无法在后续行中对反向 ID 对进行分组,以便识别这些对以便稍后更正。
表 1:问题数据示例
年月 | ParentID | ChildID |
---|---|---|
202101 | 1234 | 5678 |
202101 | 9012 | 3456 |
202102 | 5678 | 1234 |
202102 | 3456 | 9012 |
表 2:预期输出
年月 | ParentID | ChildID |
---|---|---|
202101 | 1234 | 5678 |
202102 | 5678 | 1234 |
202101 | 9012 | 3456 |
202102 | 3456 | 9012 |
解决方法
您可以使用exists
:
select t.*
from t
where exists (select 1
from t t2
where t2.parentid = t.childid and
t2.childid = t.parentid
);
,
要将反向 Id 配对在一起,您可以按 Id 列的最小值(或最大值)进行排序
select *
from t
where exists (
select *
from t t2 where t2.parentid = t.childid and t2.childid = t.parentid
)
order by case when parentId < childId then parentId else ChildId end
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。