我想在分组时将两列聚合成一个“数组”。
假设一个像这样的表:
friends_map:
=================================
user_id friend_id confirmed
=================================
1 2 true
1 3 false
2 1 true
2 3 true
1 4 false
我想从user_id中选择此表和group并获取friend_id并确认为以逗号分隔的连接值。
目前我有这个:
SELECT user_id, array_agg(friend_id) as friends, array_agg(confirmed) as confirmed
FROM friend_map
WHERE user_id = 1
GROUP BY user_id
让我:
=================================
user_id friends confirmed
=================================
1 [2,3,4] [t, f, f]
我怎样才能得到:
=================================
user_id friends
=================================
1 [ [2,t], [3,f], [4,f] ]
答案 0 :(得分:34)
SELECT user_id, array_agg((friend_id, confirmed)) as friends
FROM friend_map
WHERE user_id = 1
GROUP BY user_id
user_id | array_agg
--------+--------------------------------
1 | {"(2,true)","(3,false)","(4,false)"}
答案 1 :(得分:27)
你可以避免多维数组的丑陋并使用一些支持混合数据类型的json:
SELECT user_id, json_agg(json_build_array(friend_id, confirmed)) AS friends
FROM friends_map
WHERE user_id = 1
GROUP BY user_id
或者使用一些key : value
对,因为json允许,所以如果你愿意,你的输出将更多 semantic :
SELECT user_id, json_agg(json_build_object(
'friend_id', friend_id,
'confirmed', confirmed
)) AS friends
FROM friends_map
WHERE user_id = 1
GROUP BY user_id;
答案 2 :(得分:23)
您可以在将这些值合并到array_agg()
函数之前将它们连接在一起:
SELECT user_id, array_agg('[' || friend_id || ',' || confirmed || ']') as friends
FROM friends_map
WHERE user_id = 1
GROUP BY user_id
演示:SQL Fiddle
答案 3 :(得分:13)
在 Postgres 9.5 中,您可以获取文本数组:
SELECT user_id, array_agg(array[friend_id::text, confirmed::text])
FROM friend_map
WHERE user_id = 1
GROUP BY user_id;
user_id | array_agg
---------+--------------------------------
1 | {{2,true},{3,false},{4,false}}
(1 row)
或int数组数组:
SELECT user_id, array_agg(array[friend_id, confirmed::int])
FROM friend_map
WHERE user_id = 1
GROUP BY user_id;
user_id | array_agg
---------+---------------------
1 | {{2,1},{3,0},{4,0}}
(1 row)
答案 4 :(得分:0)
您可以使用:array[]
只需这样做:
SELECT user_id, array[friend_id, confirmed]
FROM friend_map
WHERE user_id = 1
GROUP BY 1;