9

我有一张这样的桌子:

                         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" |
4

2 回答 2

15

基于 Laurence 的回答,这是一种纯 SQL 方法,可以将求和的键/值对聚合到新的hstoreusingarray_agghstore(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为简单的整数转换并简化了键/值迭代。

于 2012-10-23T00:09:17.783 回答
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 fiddle 接受多行函数体,在真正的 postgres 中,您应该能够 $$ 引用它并将其分解一下。

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

于 2012-10-22T21:50:27.993 回答