问题描述
我正在处理超过 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