我有一个这样的表:
Table "public.statistics" id | integer | not null default nextval('statistics_id_seq'::regclass) goals | hstore |
项目:
|id |goals | |30059 |"3"=>"123" | |27333 |"3"=>"200", "5"=>"10" |
我需要做什么才能通过哈希键聚合所有值?
我想得到这样的结果:
select sum(goals) from statistics
返回
|goals | |"3"=>"323", "5"=>"10" |
在Laurence的答案的基础上,这是一种纯SQL方法,用于将总的键/值对聚合为新的hstoreusingarray_agg和hstore(text[], text[])构造函数。
hstore
array_agg
hstore(text[], text[])
http://sqlfiddle.com/#!1/9f1fb/17
SELECT hstore(array_agg(hs_key), array_agg(hs_value::text)) FROM ( SELECT s.hs_key, sum(s.hs_value::integer) FROM ( SELECT (each(goals)).* FROM statistics ) as s(hs_key, hs_value) GROUP BY hs_key ) x(hs_key,hs_value)
我还替换to_number了一个简单的整数转换并简化了键/值迭代。
to_number