Select sum of an array column in PostgreSQL

北慕城南 提交于 2019-12-03 11:08:37

问题


If I have the following table:

Table "users"
Column          |       Type       | Modifiers 
---------------+------------------+-----------
  id            | integer          | not null default nextval('users_id_seq'::regclass)
  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.


回答1:


SELECT id, (SELECT SUM(s) FROM UNNEST(monthly_usage) s) as total_usage from users;



回答2:


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


来源:https://stackoverflow.com/questions/20020832/select-sum-of-an-array-column-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!