如何基于另一列SQL中的唯一值创建数组列

问题描述 投票:0回答:1

我有一个postgres表中的数据,如下所示:

Server    |    Database    | Contact 

server1   |    db1         | contact 1
server1   |    db2         | contact 2
server1   |    db3         | contact 3 
server2   |    db1         | contact 4
server2   |    db2         | contact 3

但我需要将其转换为以这种格式传递到前端视图:

Server    | Database        | Contact 

server1   | {db1, db2, db3} | {contact1, contact2, contact3}
server2   | {db1, db2}      | {contact3, contact4} 

对于Server列中的每个唯一值,我想在SQL查询中的每个其他列中创建一个数组列。到目前为止,我有类似的东西但它似乎没有在Server列中创建一个数组(为清晰起见,排除了联系人列):

SELECT     "table1"."Server"
            COALESCE( NULLIF( array 
           ( 
                  select DISTINCT x 
                  FROM   unnest( array_agg(DISTINCT "table1"."Server") ) x 
                  WHERE  x IS NOT NULL ), '{}' ), '{"No Data"}' ) AS "serverList" , 
           COALESCE( NULLIF( array 
           ( 
                  SELECT x 
                  FROM   unnest( array_agg(DISTINCT "table1"."Database") ) x 
                  WHERE  x IS NOT NULL ), '{}' ), '{"No Data"}' ) AS "databseList"
FROM       "table1"                                     
GROUP BY   
           "table1"."Server"

如何从“服务器”列中的唯一条目中正确创建数组列?

sql postgresql coalesce array-agg
1个回答
1
投票

array_agg()怎么样?

select server, array_agg(database) as databases, array_agg(contact) as contacts
from t
group by server;

如果值必须在数组中是唯一的,请使用distinct

© www.soinside.com 2019 - 2024. All rights reserved.