Aggregate hstore column in PostreSQL

前端 未结 2 1724
星月不相逢
星月不相逢 2020-12-31 17:25

I have a table like this:

                         Table \"public.statistics\"

id         | integer                | not null default nextval(\'statistics_i         


        
2条回答
  •  太阳男子
    2020-12-31 17:58

    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.

    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)
    

    I've also replaced to_number with a simple cast to integer and simplified the key/value iteration.

提交回复
热议问题