0

数据库表如下所示:

state |  city    | contact
---------------------------
NY    |  city1   | person1;person2;person3       
NY    |  city2   | person4;person5;person6
NY    |  city3   | null
CA    |  city1   | person7;person8;person9
CA    |  city2   | person10;person11;person12 

我想按状态分组并city变成一个数组并contact用分号拆分以变成一个数组:

state   |    city.               | contact 
------------------------------------------------
NY      |  {city1, city2, city3} | {person1,person2,person3,person4,person5,person6,null}
CA      |  {city1, city2}        | {person7,person8,person9,person10,person11,person12}

这将每个状态聚合contacts为 1 行,并且应该处理空值,但它不会被拆分为分号:

select 
    t.state,
    coalesce(nullif(array(Select x from unnest(array_agg(t.contact order by t.city)) x where x is not null, '{}', '{}') as "contacts_agg"
    -- t.city, ^^ same logic as above 
from table as t 
group by 
    t.state 

如何state在聚合每个状态的所有行city和行时修改我的查询以分组?contact

4

1 回答 1

0

您可以取消嵌套联系人并重新聚合:

select t.state, array_agg(distinct city) as city, array_agg(distinct contact) as contacts
from t cross join
      regexp_split_to_table(contacts, ';') c(contact)
group by t.state;

是一个 db<>fiddle。

于 2020-05-24T02:28:16.010 回答