Postgres中多个数组的平均值

问题描述 投票:1回答:1

我想计算Postgres中多个(json)数组的平均值。

我有下表:

CREATE TABLE marks (student varchar(48), year int , testresult json);

INSERT INTO marks 
VALUES ('John',2017,'[7.3,8.1,9.2]'),
      ('Mary', 2017, '[6.1,7.4,5.6]'), 
     ('Tim',2017,'[6.3,5.6,8.3]');

2017年有3名学生参加了3次考试。我想计算2017年所有学生的平均考试成绩(n精度)。

自己尝试过,直到现在才实现以下目标:http://www.sqlfiddle.com/#!15/58f38/44

任何帮助都会非常感激,因为我对Postgres很新。所以我希望得到以下结果:

student|  year | averages   
-------+-------+-----------
All    |  2017 | [6.567, 7.033, 7.700]
sql postgresql
1个回答
1
投票

您可以使用unnest,进行计算并聚合回JSON格式:

WITH cte AS (
   SELECT 'All' AS student, year, AVG(unnest::decimal(10,2)) AS av
   FROM marks,
   unnest(ARRAY(SELECT json_array_elements_text(testresult))) with ordinality
   GROUP BY year, ordinality
)
SELECT student, year, array_to_json(array_agg(av::decimal(10,3))) AS averages
FROM cte
GROUP BY student, year;

输出:

+---------+------+---------------------+
| student | year |      averages       |
+---------+------+---------------------+
| All     | 2017 | [6.567,7.033,7.700] |
+---------+------+---------------------+

DBFiddle Demo

© www.soinside.com 2019 - 2024. All rights reserved.