Postgres中多个数组的平均值

时间:2018-05-11 17:35:16

标签: sql postgresql

我想计算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]

1 个答案:

答案 0 :(得分: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