HAIDER TAYYAB
HAIDER TAYYAB

Reputation: 47

Count the number of instances for each value in a delimited string

I have a field delimited by '->'. I want to do a total count of which value appears most or top 3

ROW 1- "Q -> Res -> tes -> Res -> twet"
ROW 2- "rw -> gewg -> tes -> Res -> twet"
ROW 3- "Y -> Res -> Res -> Res -> twet"

Answer to this example would be:

Top 1- Res |6
Top 2- tewt|3
Top 3- tes |2

Ive tried:

( select count(*)    from unnest(split(text, ' -> ')) word where word = 'Res'  ) cnt from table     

but i need to do it dynamically instead of putting in every word

Upvotes: 0

Views: 51

Answers (1)

Mikhail Berlyant
Mikhail Berlyant

Reputation: 172954

Consider below

select 'Top ' || row_number() over(order by cnt desc) rank, 
  word, cnt
from (
  select word, count(*) cnt
  from your_table, unnest(split(text, ' -> ')) word
  group by word
  order by cnt desc
  limit 3
)               

with output

enter image description here

Upvotes: 2

Related Questions