web-dev-qa-db-ja.com

PostgreSQLで配列列の合計を選択します

次の表がある場合:

_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;

これは明らかに機能しません。

21
Nicolas
SELECT id, (SELECT SUM(s) FROM UNNEST(monthly_usage) s) as total_usage from users;
33
Dmitry Seleznev

この一般化と再フォーマット Dmitry の答えは、それがどのように機能するかを理解するのに役立ちます。

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

結果:

total
 6
6
jbryanscott