I have a table like this:
Table "public.statistics"
id | integer | not null default nextval('statistics_id_seq'::regclass)
goals | hstore |
items:
|id |goals |
|30059 |"3"=>"123" |
|27333 |"3"=>"200", "5"=>"10" |
What I need to do for aggregate all values by key in hash?
I want to get result like this:
select sum(goals) from statistics
return
|goals |
|"3"=>"323", "5"=>"10" |
Building on Laurence’s answer, here’s a pure SQL way to aggregate the summed key/value pairs into a new
hstoreusingarray_aggand thehstore(text[], text[])constructor.http://sqlfiddle.com/#!1/9f1fb/17
I’ve also replaced
to_numberwith a simple cast to integer and simplified the key/value iteration.