Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select sum of an array column in PostgreSQL

Tags:

If I have the following table:

Table "users" Column          |       Type       | Modifiers  ---------------+------------------+-----------   id            | integer          |    monthly_usage | real[]           |  

Where monthly_usage is an array of 12 numbers, i.e. {1.2, 1.3, 6.2, 0.9,...}

How can I select the sum of that column?

Something along the lines of:

SELECT id, sum(monthly_usage) as total_usage from users;

Which obviously doesn't work.

like image 982
Nicolas Avatar asked Nov 16 '13 16:11

Nicolas


2 Answers

SELECT id, (SELECT SUM(s) FROM UNNEST(monthly_usage) s) as total_usage from users; 
like image 69
Dmitry Seleznev Avatar answered Sep 18 '22 04:09

Dmitry Seleznev


This generalization and reformatting Dmitry's answer helps me understand how it works:

SELECT   sum(a) AS total FROM   (     SELECT       unnest(array [1,2,3]) AS a   ) AS b 

Result:

total  6 
like image 22
jbryanscott Avatar answered Sep 22 '22 04:09

jbryanscott