postgres group by many public in array of many rows

时间:2017-12-13 20:49:37

标签: sql postgresql

我有一张这样的表:

{
"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 }
]
}

在该特定实例中,24943存在于所有5行中。如何折叠这样的表?并将数组聚合成1个平滑数组。

请记住,还有成千上万的其他行,所以我不想要一个庞大的组。我希望只有在ids数组中具有相同公共ID的行才能向下折叠

enter image description here

我可以这样做

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)

为了给出更多的范围,下面的棕色中间件的ID为24943 enter image description here

1 个答案:

答案 0 :(得分:0)

你想要的结果不是很清楚,如果你只想统一数组,试试这个:

R> df
    old_col_1 old_col_2 old_col_3 new_col_2  new_col_3
 1:        20        55 138.28667       -40 -123.28667
 2:        21        56  69.03836       -41  -54.03836
 3:        22        57 147.39790       -42 -132.39790
 4:        23        58  88.15505       -43  -73.15505
 5:        24        59  28.96437       -44  -13.96437