PostgreSQL中的聚合hstore列

时间:2012-10-22 21:34:38

标签: sql postgresql aggregate-functions postgresql-9.1 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"  |

我需要做什么来通过哈希键来聚合所有值?

我想得到这样的结果:

select sum(goals) from statistics

返回

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

2 个答案:

答案 0 :(得分:14)

在Laurence的回答的基础上,这是一种纯粹的SQL方法,可以使用hstorearray_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替换为简单的强制转换为整数并简化了键/值迭代。

答案 1 :(得分:5)

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

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小提琴接受一个多行函数体,在真正的postgres中,你应该能够引用它并稍微分解它。

http://sqlfiddle.com/#!1/e2ea7/1/0