I have data with an hstore like this:
|brand|account|likes|views |
|-----|-------|-----|----------------------|
|Ford |ford_uk|1 |"3"=>"100" |
|Ford |ford_us|2 |"3"=>"200", "5"=>"10" |
|Jeep |jeep_uk|3 |"3"=>"300" |
|Jeep |jeep_us|4 |"3"=>"400", "5"=>"20" |
I would like to be able to sum the hstores by key, grouped by brand:
|brand|likes|views |
|-----|-----|----------------------|
|Ford |3 |"3"=>"300", "5"=>"10" |
|Jeep |7 |"3"=>"700", "5"=>"20" |
This answer gives a good solution for how to do this without a GROUP BY. Adapting it to this situation gives something like:
SELECT
sum(likes) AS total_likes,
(SELECT hstore(array_agg(key), array_agg(value::text))
FROM (
SELECT s.key, sum(s.value::integer)
FROM (
SELECT((each(views)).*)
) AS s(key, value)
GROUP BY key
) x(key, value)) AS total_views
FROM my_table
GROUP BY brand
However this gives:
ERROR: subquery uses ungrouped column "my_table.views" from outer query
Any help appreciated!