可能有一些方法可以避免数字转换,但这应该可以完成工作:
SELECT
key, Sum(to_number(value, '999999999999')) FROM (
SELECT (each(goals)).key, (each(goals)).value FROM public.statistics
) as s
Group By
key
http://sqlfiddle.com/#!1/eb745/10/0
这是 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';
我无法让 sql fiddle 接受多行函数体,在真正的 postgres 中,您应该能够 $$ 引用它并将其分解一下。
http://sqlfiddle.com/#!1/e2ea7/1/0