2

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;
2
  • I think you should accept your own answer on this. Commented Jan 31, 2020 at 11:35
  • Seconded, your answer is great, wish I could give you more upvotes Commented Nov 23, 2021 at 2:41

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

As an alternative, you could just skip several steps and directly group on the unnested value:

select unnest(ner_tags) as tags,
       count(*) as cnt
from message_tags
group by tags
order by cnt desc

Since you only require a count over each of the values (no distinct or other aggregates), this is the simplest solution.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.