简体   繁体   中英

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. how do I collapse down a table like this? and aggregate the arrays into 1 smooth array.

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

在此处输入图片说明

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 在此处输入图片说明

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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