数据库表如下所示:
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