web_student
web_student

Reputation: 186

Average from multiple arrays in Postgres

I want to calculate the average from multiple (json) arrays in Postgres.

I have the following table:

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]');

There are 3 students in 2017 that all have taken 3 tests. I want to calculate the average of the tests for all students in 2017 (with n precision).

Have tried it myself, and only achieved the following until now: http://www.sqlfiddle.com/#!15/58f38/44

So I want to get the following result:

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

Upvotes: 1

Views: 1245

Answers (1)

Lukasz Szozda
Lukasz Szozda

Reputation: 175586

You could use unnest, do calculation and aggregate back to JSON format:

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;

Output:

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

DBFiddle Demo

Upvotes: 1

Related Questions