将列的所有唯一值转换为GROUPY BY查询的返回列中的集合或数组

时间:2016-06-14 17:45:33

标签: sql postgresql aggregation

我有以下查询:

SELECT COUNT(*) count, userid, displaydate 
FROM data 
GROUP BY userid, displaydate 
HAVING COUNT(userid) > 1

我想修改它以包含另一列type,以便我可以创建一个包含每个组发生的所有唯一type值的数组。例如,如果我有这样的数据:

userid, displaydate, type
a,      1242242422,   0
a,      1242242422,   1

我怎样才能收到以下内容:

(a, 1242242422, [0, 1])

1 个答案:

答案 0 :(得分:0)

使用array_agg

SELECT userid, displaydate, array_agg(distinct type)
-- use array_agg(distinct type order by type) if the type needs to be ordered
FROM data 
GROUP BY userid, displaydate 
HAVING COUNT(*) > 1