简体   繁体   English

postgres按公共ID在多行数组中分组

[英]postgres group by common id in array on many rows

I have a table like this: 我有一张这样的桌子:

{
"type": "FeatureCollection",
"name": "test",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "final_zone": "ECZ", "id": 20753, "ids": "{22210,10959,22209,22213}", "sub": "{ECZECSZ,NULL,ECZECSZ,ECZECSZ}" }, "geometry": null },
{ "type": "Feature", "properties": { "final_zone": "Protection", "id": 6516, "ids": "{24920,24943}", "sub": "{NULL,NULL}" }, "geometry": null },
{ "type": "Feature", "properties": { "final_zone": "Protection", "id": 6524, "ids": "{24912,24920,24943,24971,24944}", "sub": "{NULL,NULL,NULL,NULL,NULL}" }, "geometry": null },
{ "type": "Feature", "properties": { "final_zone": "Protection", "id": 6528, "ids": "{24943,24958,24944}", "sub": "{NULL,NULL,NULL}" }, "geometry": null },
{ "type": "Feature", "properties": { "final_zone": "Protection", "id": 6610, "ids": "{24943,24971}", "sub": "{NULL,NULL}" }, "geometry": null },
{ "type": "Feature", "properties": { "final_zone": "Protection", "id": 6781, "ids": "{24912,24906,24943}", "sub": "{NULL,NULL,NULL}" }, "geometry": null }
]
}

In this particular instance 24943 is present in all 5 rows. 在此特定实例中,所有5行中都存在24943。 how do I collapse down a table like this? 我该如何折叠这样的桌子? and aggregate the arrays into 1 smooth array. 并将阵列汇总为1个平滑阵列。

Keep in mind there are thousands of other rows so I dont want one massive group by. 请记住,还有成千上万的其他行,所以我不要一个庞大的组。 I want JUST the rows that have the same common ID in the ids array to be collapse down 我只想将ids数组中具有相同公共ID的行折叠起来

在此处输入图片说明

I can do this 我可以做这个

with abid as(
select regexp_replace(id,'[{}]','','gi')::int id from(
    select unnest(ids) id from(
        select string_to_array(ids,',') ids from conflict.test
        )t
    )t2
),
abid2 as(select ids::int[] id from conflict.test
    )
select t2.*,t.* from abid t,abid2 t2 where t.id =any(t2.id)

just to give a little more scope the brown middle piece below has the id of 24943 只是为了给更多的范围,下面的棕色中间部分的ID为24943 在此处输入图片说明

Is not so clear the result you want, if you just want to unify the array, try this: 不清楚您想要的结果,如果您只是想统一数组,请尝试以下操作:

with tmp as (
select unnest(ids) ids
from your_table_name
group by unnest(ids)
)
select x.final_zone, x.id, array_agg(t.ids), x.sub, x.polys
from tmp t
cross join your_table_name x
group by x.final_zone, x.id, x.sub, x.polys;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM