可以使用postgres获取json数组中值的平均值吗? [英] Can get an average of values in a json array using postgres?

查看:187
本文介绍了可以使用postgres获取json数组中值的平均值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

postgres的一大优点是它允许索引到json对象.

One of the great things about postgres is that it allows indexing into a json object.

我有一列数据的格式如下:

I have a column of data formatted a little bit like this:

{"Items":
  [
    {"RetailPrice":6.1,"EffectivePrice":0,"Multiplier":1,"ItemId":"53636"},
    {"RetailPrice":0.47,"EffectivePrice":0,"Multiplier":1,"ItemId":"53404"}
  ]
}

我想做的是找到包含这些数据的每一行的平均RetailPrice.

What I'd like to do is find the average RetailPrice of each row with these data.

类似

select avg(json_extract_path_text(item_json, 'RetailPrice')) 

但实际上我需要对项目json对象中的每个项目执行此操作.因此,对于此示例,查询的单元格中的值为3.285

but really I need to do this for each item in the items json object. So for this example, the value in the queried cell would be 3.285

我该怎么做?

推荐答案

可以像这样工作:

WITH cte(tbl_id, json_items) AS ( 
   SELECT 1
        , '{"Items": [
       {"RetailPrice":6.1,"EffectivePrice":0,"Multiplier":1,"ItemId":"53636"}
      ,{"RetailPrice":0.47,"EffectivePrice":0,"Multiplier":1,"ItemId":"53404"}]}'::json
   )
SELECT tbl_id, round(avg((elem->>'RetailPrice')::numeric), 3) AS avg_retail_price
FROM   cte c
     , json_array_elements(c.json_items->'Items') elem
GROUP  BY 1;

CTE只是代替了像这样的表:

The CTE just substitutes for a table like:

CREATE TABLE tbl (
   tbl_id     serial PRIMARY KEY
 , json_items json
);

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆