Вы можете использовать боковое соединение и regexp_split_to_table()
, чтобы разбить строку, а затем агрегировать:
select t.id, s.fruit, count(*)
from mytable t
cross join lateral regexp_split_to_table(t.comma_string, ', ') s(fruit)
group by t.id, s.fruit
order by t.id, s.fruit
Демонстрация на DB Fiddle :
id | fruit | count
:----- | :------ | ----:
abc123 | apples | 2
abc123 | bananas | 1
abc123 | oranges | 1
abc123 | pears | 1
def456 | apples | 1
def456 | carrots | 1
def456 | grapes | 1
def456 | pears | 1