Select sum of an array column in PostgreSQL

后端 未结 3 1944
被撕碎了的回忆
被撕碎了的回忆 2021-02-05 06:07

If I have the following table:

Table \"users\"
Column          |       Type       | Modifiers 
---------------+------------------+-----------
  id            | i         


        
相关标签:
3条回答
  • 2021-02-05 06:40

    In several ways to add up the values ​​of the array, the form I always use is:

    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
    

    Result:

    138
    

    For more information https://www.postgresql.org/docs/9.1/queries-with.html

    0 讨论(0)
  • 2021-02-05 06:53
    SELECT id, (SELECT SUM(s) FROM UNNEST(monthly_usage) s) as total_usage from users;
    
    0 讨论(0)
  • 2021-02-05 06:56

    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
    
    0 讨论(0)
提交回复
热议问题