本文介绍了在PostreSQL中汇总hstore列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的表:
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" |
我需要做的是通过键入哈希值来汇总所有值吗?
What I need to do for aggregate all values by key in hash?
我想得到这样的结果:
select sum(goals) from statistics
返回
|goals |
|"3"=>"323", "5"=>"10" |
推荐答案
基于Laurence的答案,这是一种纯SQL方法使用 array_agg
和 hstore将总的键/值对汇总为新的
构造函数。 hstore
[],text [])
Building on Laurence's answer, here's a pure SQL way to aggregate the summed key/value pairs into a new hstore
using array_agg
and the hstore(text[], text[])
constructor.
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
并简化了键/值迭代。
I've also replaced to_number
with a simple cast to integer and simplified the key/value iteration.
这篇关于在PostreSQL中汇总hstore列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!