2016-11-07 59 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;