在PostgreSQL中选择数组列的总和

时间:2013-11-16 16:29:08

标签: postgresql postgresql-9.1

如果我有下表:

Table "users"
Column          |       Type       | Modifiers 
---------------+------------------+-----------
  id            | integer          | not null default nextval('users_id_seq'::regclass)
  monthly_usage | real[]           | 

其中monthly_usage是包含12个数字的数组,即{1.2, 1.3, 6.2, 0.9,...}

如何选择该列的总和?

有些事情:

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

这显然不起作用。

3 个答案:

答案 0 :(得分:29)

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

答案 1 :(得分:4)

这种概括和重新格式化Dmitry的答案有助于我理解它的工作原理:

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

结果:

total
 6

答案 2 :(得分:0)

通过几种方式将数组的值相加,我一直使用的形式是:

WITH X AS(
    SELECT unnest(ARRAY[1, 5, 0, 12, 1, 0, 30, 20, 8, 3, 15, 15, 20, 8]) AS VALOR
)
SELECT SUM(VALOR) FROM X

结果:

138

有关更多信息,https://www.postgresql.org/docs/9.1/queries-with.html