如何使用数据类型Array获取postgres列中的计数

时间:2016-12-22 16:43:41

标签: ruby-on-rails ruby postgresql

如何在postgres中找出数据类型为数组的ruby中元素的数量

Table in postgres
id | user_id | interests
---|---------|------------
1  | 1       | [1,2,3,4,5]
2  | 4       | [2,3]
3  | 2       | [2,5]


output: {1 => 1, 2 => 3, 3 => 2, 4 => 1, 5 => 2}

1 个答案:

答案 0 :(得分:0)

select val, count(*)
from (
        select unnest( z ) as val
        from (
            values
                    (1, 1, array[1,2,3,4,5]),
                    (2, 4, array[2,3]),
                    (3, 2, array[2,5])
            ) as x(x,y,z)
) x
group by val
order by 1

val |count |
----|------|
1   |1     |
2   |3     |
3   |2     |
4   |1     |
5   |2     |