如何在Postgres中“折叠”数组值?

时间:2013-03-06 13:14:56

标签: postgresql

我是Postgresql的新手,我想知道是否可以计算以下内容:

select T.result + 
    -- here I want to do the following:
    -- iterate through T.arr1 and T.arr2 items and add their values
    -- to the T.result using the rules:
    -- if arr1 item is 1 then add 10, if arr1 item is 2 or 3 then add 20,
    -- if arr2 item is 3 then add 15, if arr2 item is 4 then add 20, else add 30

from (
    select 5 as result, array[1,2,3] as arr1, array[3,4,5] as arr2
) as T

因此,对于这些数组,查询将产生:5 + 10 + 20 + 20 + 15 + 20 + 30 = 120。

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

尝试类似:

SELECT SUM(CASE val 
           WHEN 1 THEN 10
           WHEN 2 THEN 20
           WHEN 3 THEN 20
           END)
FROM unnest(array[1,2,3]) as val

获得数组的总和。

完整查询将如下所示:

select T.result + 
       (SELECT SUM(CASE val 
               WHEN 1 THEN 10
               WHEN 2 THEN 20
               WHEN 3 THEN 20
               END)
        FROM  unnest(arr1) as val) +
       (SELECT SUM(CASE val 
               WHEN 3 THEN 15
               WHEN 4 THEN 20
               ELSE 30
               END)
        FROM  unnest(arr2) as val)   
from (
    select 5 as result, array[1,2,3] as arr1, array[3,4,5] as arr2
) as T

SQLFiddle