如何从jsonb返回一个对象数组?

时间:2015-07-22 20:10:52

标签: postgresql postgresql-9.4 jsonb

我有下表:

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

使用以下数据:

INSERT INTO mytable (employee, data)
VALUES
 ('Jim', '{"sales_tv": [{"value": 10, "yr": "2010", "loc": "us"}, {"value": 5, "yr": "2011", "loc": "europe"}, {"value": 40, "yr": "2012", "loc": "asia"}], "sales_radio": [{"value": 11, "yr": "2010", "loc": "us"}, {"value": 8, "yr": "2011", "loc": "china"}, {"value": 76, "yr": "2012", "loc": "us"}], "another_key": "another value"}'),
 ('Rob', '{"sales_radio": [{"value": 7, "yr": "2014", "loc": "japan"}, {"value": 3, "yr": "2009", "loc": "us"}, {"value": 37, "yr": "2011", "loc": "us"}], "sales_tv": [{"value": 4, "yr": "2010", "loc": "us"}, {"value": 18, "yr": "2011", "loc": "europe"}, {"value": 28, "yr": "2012", "loc": "asia"}], "another_key": "another value"}')

请注意除了“sales_tv”和“sales_radio”之外还有其他键。对于下面的查询,我只需要关注“sales_tv”和“sales_radio”。

我正在尝试为任何以“sales_”开头的内容返回Jim的对象列表。在列表中的每个对象中,我只需要返回值和yr(忽略“位置”或任何其他键),例如:

    employee |  sales_
    Jim      |  {"sales_tv": [{"value": 10, "yr": "2010"}, {"value": 5, "yr": "2011"}, {"value": 40, "yr": "2012"}],
                 "sales_radio": [{"value": 11, "yr": "2010"}, {"value": 8, "yr": "2011"}, {"value": 76, "yr": "2012"}]}

我能够获得每个值,但没有年份,也没有我想要的列表格式:

SELECT t.employee, json_object_agg(a.k, d.value) AS sales
FROM   mytable t
     , jsonb_each(t.data)      a(k,v) 
     , jsonb_to_recordset(a.v) d(yr text, value float)
WHERE  t.employee = 'Jim'
AND    a.k LIKE 'sales_%'
GROUP  BY 1

结果:

employee    | sales
----------  | --------
Jim         | { "sales_tv" : 10, "sales_tv" : 5, "sales_tv" : 40, "sales_radio" : 11, "sales_radio" : 8, "sales_radio" : 76 }

1 个答案:

答案 0 :(得分:0)

原则与the question you asked yesterday相同,第一个查询(即使这个问题是昨天的第二个查询):剥离json数据中的层次结构层,然后用任何数据重新组合它您感兴趣的数据,采用新的json格式。

SELECT employee, json_object_agg(k, jarr) AS sales
FROM (
  SELECT t.employee, a.k,
         json_agg(json_build_object('value', d.value, 'yr', d.yr)) AS jarr
  FROM mytable t,
       jsonb_each(t.data) a(k, v),
       jsonb_to_recordset(a.v) d(yr text, value float)
  WHERE t.employee = 'Jim'
    AND a.k like 'sales_%'
  GROUP BY 1, 2) sub
GROUP BY 1; 

FROM子句中,使用jsonb_eachjsonb_to_recordset等函数分解JSON层次结构。正如最后一个函数的名称所暗示的那样,每个函数都会生成一组可以使用的记录,就像使用任何其他表及其列一样。在列选择列表中,选择所需的数据以及相应的聚合函数json_aggjson_object_agg以将JSON结果重新组合在一起。对于每个层次结构,您需要一个聚合函数,因此需要一个级别的子查询。