2016-11-07 30 views
0

我想指望通过以下方式字符串中包含的元素:从串计数不同元素的PostgreSQL

row features 
1 'a | b | c' 
2 'a | c' 
3 'b | c | d' 
4 'a' 

结果:

feature count 
a  3 
b  2 
c  3 
d  1 

我已经找到了解决方案通过寻找最多数量的特征并将每个特征分成1列,所以feature1 =字符串中特征1的内容,但我必须手动合计数据。像我的例子一样,必须有一个明智的方法来做到这一点。

回答

0

我用regexp_split_to_table

SELECT regexp_split_to_table(feature, E' \\| ') AS k, count(*) 
FROM tab1 
GROUP BY k 
2

通过使用unnest()这个归一化的数据变成了简单group by

select trim(f.feature), count(*) 
from the_table t 
    cross join lateral unnest(string_to_array(t.features, '|')) as f(feature) 
group by trim(f.feature) 
order by 1;