I have the following table:
CREATE TABLE mytable (
id serial PRIMARY KEY
, employee text UNIQUE NOT NULL
, data jsonb
);
With t
Your first query can be solved like this (shooting from the hip, no access to PG 9.4 here):
SELECT employee, json_object_agg(key, sales)::jsonb AS sales_
FROM (
SELECT t.employee, j.key, sum((e->>'value')::int) AS sales
FROM mytable t,
jsonb_each(t.data) j,
jsonb_array_elements(j.value) e
WHERE t.employee = 'Jim'
AND j.key like 'sales_%'
AND e->>'yr' = '2012'
GROUP BY t.employee, j.key) sub
GROUP BY employee;
The trick here is that you use LATERAL
joins to "peel away" outer layers of the jsonb
object to get at data deeper down. This query is assuming that Jim may have sales in multiple locations.
(Working on your query 2)