数组的Postgres频率计数

时间:2018-07-23 19:31:05

标签: postgresql

我有一列文字[]。如何获得列中所有对象的频率计数?

示例:

col_a   
--------
{a, b}   
{a}    
{b}    
{a}  

输出应为:

col_a   | count 
----------------    
a       | 3   
b       | 2    

我的查询:

with all_tags as (
select array_agg(c)
from (
  select unnest(tags)
  from message_tags
) as dt(c)
)

select count(*) from all_tags;

1 个答案:

答案 0 :(得分:0)

弄清楚了:

-- Collapse all tags into one array
with all_tags as (
select array_agg(c) as arr
from (
  select unnest(ner_tags)
  from message_tags
) as dt(c)
),

-- Expand single array into a row per tag
row_tags as (
select unnest(arr) as tags from all_tags
)

-- count distinct tags
select tags, count(*) from row_tags group by tags