从JSON列计算平均值 [英] Calculate average from JSON column

查看:156
本文介绍了从JSON列计算平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表,其中包含一列要从中提取信息的JSON数据.具体来说,我只想获取平均值.

I have a table with a column of JSON data that I want to extract information from. Specifically I just want to get the average value.

我所拥有的例子

id      speed_data
391982  [{"speed":1.3,"speed":1.3,"speed":1.4,"speed":1.5...
391983  [{"speed":0.9,"speed":0.8,"speed":0.8,"speed":1.0...

我想要的例子:

id      speed_data
391982  1.375
391982  0.875

有关如何使该查询正常工作的任何建议?

Any suggestions on how to get this query to work?

select t.*, avg(x.speed)
from tbl t,
    json_array_elements(a->'speed') x
order by random()
limit 1

推荐答案

您的json数组被弄乱了,就像

Your json array is messed up, like @posz commented. Would have to be:

CREATE TABLE tbl (id int, speed_data json);

INSERT INTO tbl VALUES
  (391982, '{"speed":[1.3,1.3,1.4,1.5]}')
, (391983, '{"speed":[0.9,0.8,0.8,1.0]}');

您的查询也以多种方式扭曲.将在pg 9.3 中如此工作:

You query is twisted in multiple ways, too. Would work like this in pg 9.3:

SELECT t.id, avg(x::text::numeric) AS avg_speed
FROM   tbl t
     , json_array_elements(speed_data->'speed') x
GROUP  BY t.id;

SQL小提琴.

在即将到来的pg 9.4 中,我们可以使用新的json_array_elements_text()进行简化(强制转换中也不太容易出错):

In the upcoming pg 9.4 we can simplify with the new json_array_elements_text() ( also less error-prone in the cast):

SELECT t.id, avg(x::numeric) AS avg_speed
FROM   tbl t
     , json_array_elements_text(speed_data->'speed') x
GROUP  BY t.id;

更多详细信息:

此外:将其存储为纯数组(numeric[],而不是json)或以规范化模式存储会更加有效.

Aside: It would be much more efficient to store this as plain array (numeric[], not json) or in a normalized schema to begin with.

这篇关于从JSON列计算平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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