【发布时间】:2020-05-24 02:19:04
【问题描述】:
DB 表如下所示:
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 行?
【问题讨论】:
标签: postgresql group-by array-agg