在PostreSQL中聚合hstore列

在PostreSQL中聚合hstore列,sql,postgresql,aggregate-functions,postgresql-9.1,hstore,Sql,Postgresql,Aggregate Functions,Postgresql 9.1,Hstore,我有一张这样的桌子: Table "public.statistics" id | integer | not null default nextval('statistics_id_seq'::regclass) goals | hstore | select sum(goals) from statistics 项目: |id |goals

我有一张这样的桌子:

                         Table "public.statistics"

id         | integer                | not null default nextval('statistics_id_seq'::regclass)
goals      | hstore                 | 
select sum(goals) from statistics
项目:

|id    |goals                  |
|30059 |"3"=>"123"             |
|27333 |"3"=>"200", "5"=>"10"  |
我需要做什么来按散列中的键聚合所有值

我想得到这样的结果:

                         Table "public.statistics"

id         | integer                | not null default nextval('statistics_id_seq'::regclass)
goals      | hstore                 | 
select sum(goals) from statistics
返回

|goals                 |
|"3"=>"323", "5"=>"10" |

可能有一些方法可以避免数字转换,但这应该可以完成工作:

SELECT 
  key, Sum(to_number(value, '999999999999')) FROM (
  SELECT (each(goals)).key, (each(goals)).value FROM public.statistics
) as s
Group By
  key

这是一种很大的气味,Postgres不想这样弯曲,但是:

create table test (id int, goals hstore);

Insert Into Test(id, goals) Values (30059, '3=>123');
Insert Into Test(id, goals) Values (27333, '3=>200,5=>10');

Create Function hagg() returns hstore As 
'Declare ret hstore := ('''' :: hstore); i hstore; c cursor for Select hstore(key, (x.Value::varchar)) From (Select key, Sum((s.value::int)) as Value From (Select (each(goals)).* From Test) as s Group By key) as x; BEGIN Open c; Loop Fetch c into i; Exit When Not FOUND; ret := i || ret; END LOOP; return ret; END' Language 'plpgsql';
我无法让SQLFiddle接受多行函数体,在真正的postgres中,您应该能够$$引用此函数并将其分解


基于Laurence的答案,这里有一种纯SQL方法,可以使用
数组_agg
hstore(text[],text[])
构造函数将求和的键/值对聚合成一个新的
hstore


我还将
转换为_number
替换为一个简单的转换为整数,并简化了键/值迭代。

是的,我尝试过这个解决方案,但我需要在
目标
列中将结果转换为哈希(hstore type)。