cva*_*vax 6 sql postgresql graph connected-components
我的桌子有account_id和device_id.一个account_id可以有多个device_ids,反之亦然.我试图计算每个连接的多对多关系的深度.
例如:
account_id | device_id
1 | 10
1 | 11
1 | 12
2 | 10
3 | 11
3 | 13
3 | 14
4 | 15
5 | 15
6 | 16
Run Code Online (Sandbox Code Playgroud)
如何构建一个知道将1-3帐户组合在一起,4-5组合在一起,并自行离开6的查询?帐户1-3的所有7个条目应该组合在一起,因为它们在某个时刻都触及了相同的account_id或device_id.我试图将它们组合在一起并输出计数.
帐户1在设备10,11,12上使用.这些设备也使用其他帐户,因此我们希望将它们包含在组中.他们使用了额外的帐户2和3.但帐户3被另外2个设备进一步使用,因此我们也将其包括在内.群组的扩展会带来任何其他帐户或设备,这些帐户或设备也"触及"该群组中已有的帐户或设备.
图表如下所示:
您可以使用递归 cte:
with recursive t(account_id, device_id) as (
select 1, 10 union all
select 1, 11 union all
select 1, 12 union all
select 2, 10 union all
select 3, 11 union all
select 3, 13 union all
select 3, 14 union all
select 4, 15 union all
select 5, 15 union all
select 6, 16
),
a as (
select distinct t.account_id as a, t2.account_id as a2
from t join
t t2
on t2.device_id = t.device_id and t.account_id >= t2.account_id
),
cte as (
select a.a, a.a2 as mina
from a
union all
select a.a, cte.a
from cte join
a
on a.a2 = cte.a and a.a > cte.a
)
select grp, array_agg(a)
from (select a, min(mina) as grp
from cte
group by a
) a
group by grp;
Run Code Online (Sandbox Code Playgroud)
这是一个 SQL Fiddle。
| 归档时间: |
|
| 查看次数: |
387 次 |
| 最近记录: |