我有一张表表示一个图表:
| FROM_ID | TO_ID |
-------------------
| 1 | 9 |
| 1 | 8 |
| 1 | 7 |
| 2 | 7 |
| 2 | 8 |
| 3 | 9 |
| 3 | 7 |
| 4 | 6 |
| 4 | 8 | 在实际示例中,有~5M行,其中~5k是唯一的,而~100 k是唯一的
我想找到所有对(FROM_ID_X,FROM_ID_Y) s.t。每个TO_ID的FROM_ID集合是另一个FROM_ID的严格超集。
所以在这个例子中我会得到:(1,2), (1,3)
为了更清楚地说明这一点:每行表示图中的一条边。图中的每个节点要么是A型,要么是B型。一个A型节点连接到一个或多个B型节点。我想找A s.t型的一对节点。其中一个指向另一个严格子集。
使用postgres fwiw
发布于 2017-01-05 22:44:58
使用array_agg将to _id连接到数组中。此后,使用self join操作符<@检查一个数组是否是另一个数组的严格超集。
with concatenated_to as (
select from_id, array_agg(to_id) as arr_to
from t
group by from_id
)
select c1.from_id,c2.from_id
from concatenated_to c1
join concatenated_to c2 on c1.from_id<>c2.from_id
where c2.arr_to <@ c1.arr_toSample Demo
发布于 2017-01-05 22:22:44
以下是一种方法:
select t.from_id, t2.from_id
from (select t.*, count(*) over (partition by from_id) as cnt
from t
) t left join
(select t.*, count(*) over (partition by from_id) as cnt
from t
) t2
on t.to_id = t2.to_id and t2.cnt = t.cnt
group by t.from_id, t2.from_id
having count(*) = count(t2.from_id);https://stackoverflow.com/questions/41495670
复制相似问题