在 PostgreSQL 中选择数组列的总和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20020832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 01:11:37  来源:igfitidea点击:

Select sum of an array column in PostgreSQL

postgresqlpostgresql-9.1

提问by Nicolas

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_usageis an array of 12 numbers, i.e. {1.2, 1.3, 6.2, 0.9,...}

monthly_usage12个数字的数组在哪里,即{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;

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

Which obviously doesn't work.

这显然不起作用。

回答by Dmitry Seleznev

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

回答by jbryanscott

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

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

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

Result:

结果:

total
 6