Разделить строку и сгруппировать по для агрегации - PullRequest
0 голосов
/ 31 января 2020

У меня есть данные вида:

id  |  comma_string
abc123  | apples, pears, bananas
def456  | carrots, grapes, apples, pears
abc123  | oranges, apples

Я бы хотел:

id | fruit  | count
abc123  |  apples | 2
abc123  |  pears | 1
abc123  |  bananas | 1
abc123  |  oranges | 1
def456  |  carrots | 1
etc...

Как я могу это получить?

1 Ответ

1 голос
/ 31 января 2020

Вы можете использовать боковое соединение и 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
...