分组时,我想将两列汇总为一个“数组”。
假设这样的表:
friends_map: ================================= user_id friend_id confirmed ================================= 1 2 true 1 3 false 2 1 true 2 3 true 1 4 false
我想从该表中选择并按user_id分组,并获取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] ]
您可以将这些值连接在一起,然后再将其输入到array_agg()函数中:
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