Postgres frequency count across arrays

女生的网名这么多〃 提交于 2021-01-28 06:46:52

问题


I have a column of text[]. How do I get a frequency count of all the objects across the column?

Example:

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

Output should be:

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

My query:

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

select count(*) from all_tags;

回答1:


figured it out:

-- 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


来源:https://stackoverflow.com/questions/51486004/postgres-frequency-count-across-arrays

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!