我想在分组时将两列聚合成一个"数组".
假设一个像这样的表:
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] ]
Ivan Burluts.. 40
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)"}
Eggplant.. 33
你可以避免多维数组的丑陋,并使用一些支持混合数据类型的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允许,所以如果你喜欢你的输出会更加语义:
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;
这绝对是正确的答案,作为json(无论如何我们都希望得到),您会得到不错的结果,并且看起来像[[1990,“ pm25”],[1995,“ pm25”],[2000,“ pm25 “]] (2认同)
Hart CO.. 25
您可以在将它们输入array_agg()
函数之前将它们连接在一起:
SELECT user_id, array_agg('[' || friend_id || ',' || confirmed || ']') as friends FROM friends_map WHERE user_id = 1 GROUP BY user_id
演示:SQL小提琴
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)"}
你可以避免多维数组的丑陋,并使用一些支持混合数据类型的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允许,所以如果你喜欢你的输出会更加语义:
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;
您可以在将它们输入array_agg()
函数之前将它们连接在一起:
SELECT user_id, array_agg('[' || friend_id || ',' || confirmed || ']') as friends FROM friends_map WHERE user_id = 1 GROUP BY user_id
演示:SQL小提琴
在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)