Sql 拆分字符串并按分组以进行聚合
我有以下表格的数据:Sql 拆分字符串并按分组以进行聚合,sql,postgresql,csv,group-by,Sql,Postgresql,Csv,Group By,我有以下表格的数据: 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 def45
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...
如何获得该值?您可以使用横向联接和
regexp\u split\u to\u 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
:
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
id |水果|计数
:----- | :------ | ----:
abc123 |苹果| 2
abc123 |香蕉| 1
abc123 |橙子| 1
abc123 |梨| 1
def456 |苹果| 1
def456胡萝卜1
def456 |葡萄| 1
def456 |梨| 1
太好了,非常感谢。我发现这一部分很难理解发生了什么
交叉连接横向regexp\u split\u到表(t.comma\u string,,')s(fruit)
,我将阅读一些更具体的内容,这一行末尾的这一部分做了什么<代码>s(水果)Welcome@DougFir. s(fruit)
为由regexp\u split\u to\u table()
生成的派生表分配一个表别名和一个列别名。这对我来说只是一种新语法,我从来没有同时为表和列创建过别名。再次感谢,这很有效