简体   繁体   English

从JSON列计算平均值

[英]Calculate average from JSON column

I have a table with a column of JSON data that I want to extract information from. 我有一个表,其中包含一列要从中提取信息的JSON数据。 Specifically I just want to get the average value. 具体来说,我只想获取平均值。

Example of what I have: 我所拥有的例子:

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...

Example of what I want: 我想要的例子:

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

Your json array is messed up, like @posz commented . 您的json数组被弄乱了,就像@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]}');

You query is twisted in multiple ways, too. 您的查询也以多种方式扭曲。 Would work like this in pg 9.3 : 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 Fiddle. SQL提琴。

In the upcoming pg 9.4 we can simplify with the new json_array_elements_text() ( also less error-prone in the cast): 在即将到来的pg 9.4中,我们可以使用新的json_array_elements_text()进行简化(在json_array_elements_text()也不太容易出错):

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

More Details: 更多细节:

Aside: It would be much more efficient to store this as plain array ( numeric[] , not json ) or in a normalized schema to begin with. 另外:将其存储为纯数组( numeric[] ,而不是json )或以规范化模式存储会更加有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM