次の表がある場合:
_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;
これは明らかに機能しません。
SELECT id, (SELECT SUM(s) FROM UNNEST(monthly_usage) s) as total_usage from users;
この一般化と再フォーマット Dmitry の答えは、それがどのように機能するかを理解するのに役立ちます。
SELECT
sum(a) AS total
FROM
(
SELECT
unnest(array [1,2,3]) AS a
) AS b
結果:
total
6