1

I've desinged a table below constructures.

         Column          |           Type           | Collation | Nullable | Default
-------------------------+--------------------------+-----------+----------+---------
 counts                  | integer[]                |           |          |      
  1. All of value in field of counts has 9 elements.
  2. All of elements is not null.

I would like to get the sum of transposed array like the below python code with using only SQL query.

import numpy as np
counts = np.array([
    [ 0,  1,  2,  3],
    [ 4,  5,  6,  7],
    [ 8,  9, 10, 11]
    ])

counts = counts.transpose()

sum = list(map(lambda x: sum(x), counts))
print(sum) # [12, 15, 18, 21]

So given example data:

 counts                | 
-----------------------|
{0,15,8,6,10,12,4,0,5} | 
{0,4,6,14,7,9,8,0,9}   |
{0,6,7,4,11,6,10,0,10} |

Because the record has over thousand, it takes much time 500ms to get response to calculate the sum of transpose in frontend side.

I would like a result:

 counts                    |  
---------------------------|
{0,25,21,24,28,27,22,0,24} | 

or

 value0 | value1 | value2 | value3 | value4 | value5 | value6 | value7 | value8 |
--------|--------|--------|--------|--------|--------|--------|--------|--------|
 0      | 25     | 21     | 24     | 28     | 27     | 22     | 0      | 24     | 

In my opinion, this question could be solved using SQL functions but I don't know how to use it.

tkgstrator
  • 11
  • 3
  • Does this answer your question? [Pairwise array sum aggregate function?](https://stackoverflow.com/questions/24997131/pairwise-array-sum-aggregate-function) – JvdV Jun 23 '22 at 13:32

1 Answers1

1

Just SUM() the array elements:

SELECT SUM(i[1]) -- first
    ,   SUM(i[2]) -- second
    ,   SUM(i[3]) -- third
-- etc.
    ,   SUM(i[9])
FROM    (VALUES
('{0,15,8,6,10,12,4,0,5}'::int[]),
('{0,4,6,14,7,9,8,0,9}'),
('{0,6,7,4,11,6,10,0,10}')) s(i);
Frank Heikens
  • 117,544
  • 24
  • 142
  • 135