【问题标题】:Postgres how to group by 1 column and aggregate other columns as elements in an arrayPostgres如何按1列分组并将其他列聚合为数组中的元素
【发布时间】: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 分组,同时聚合每个州的所有citycontact 行?

【问题讨论】:

    标签: postgresql group-by array-agg


    【解决方案1】:

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

    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;
    

    Here 是一个 dbfiddle。

    【讨论】:

    • 我首先需要做几个内部连接才能到达contact 列。假设contact 是我可以作为两个内部连接的结果访问的列,当我添加此逻辑时,我收到一条错误消息"there is an entry for table .... but it cannot be referenced in this part of the query"
    • @elvis 。 . .这不仅回答了您的问题,而且提供了一个 db fiddle 来说明它的工作原理。您可以将现有查询设为 CTE。如果你想不出你问了一个新的问题。这个回答了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-27
    • 2011-04-11
    • 2017-04-06
    相关资源
    最近更新 更多