[英]How to create array column based on unique values in another column SQL
I have data from a postgres tables that looks like this: 我有一个来自postgres表的数据,看起来像这样:
Server | Database | Contact
server1 | db1 | contact 1
server1 | db2 | contact 2
server1 | db3 | contact 3
server2 | db1 | contact 4
server2 | db2 | contact 3
But I need to transform it to pass to a front end view in this format: 但是我需要将其转换为以下格式的前端视图:
Server | Database | Contact
server1 | {db1, db2, db3} | {contact1, contact2, contact3}
server2 | {db1, db2} | {contact3, contact4}
For every unique value in the Server
column I want to create an array column out of every other column in my SQL query. 对于Server
列中的每个唯一值,我想在SQL查询中的所有其他列之外创建一个数组列。 So far I have something like this but it does not seem to create an array out of the Server
column (Contact column excluded for clarity): 到目前为止,我有类似的内容,但是它似乎并未在Server
列之外创建一个数组(为清晰起见,Contact列已排除):
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"
How can I correctly create array columns out of unique entries in the Server column? 如何从“服务器”列中的唯一条目中正确创建阵列列?
How about array_agg()
? array_agg()
呢?
select server, array_agg(database) as databases, array_agg(contact) as contacts
from t
group by server;
If the values need to be unique in the arrays, use distinct
. 如果值在数组中需要唯一,请使用distinct
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.