How do I return a jsonb array and array of objects from my data?

前端 未结 2 666
清酒与你
清酒与你 2020-12-21 17:43

I have the following table:

CREATE TABLE mytable (
  id       serial PRIMARY KEY
, employee text UNIQUE NOT NULL
, data     jsonb
);

With t

2条回答
  •  [愿得一人]
    2020-12-21 18:30

    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)

提交回复
热议问题