从多行获取列值作为数组

时间:2014-02-24 16:15:55

标签: sql postgresql aggregate-functions postgresql-8.4 window-functions

我正在尝试将列值作为数组提取,以便在function array_agg_transfn() to calculate the median value as defined in the Postgres Wiki.

中使用它们

我根据当前行获取的特定列的列值。例如,当前行下面的13行。我尝试使用以下查询:

select a."Week_value", 
       array_agg(a."Week_value") 
            over(order by prod_name,week_date desc 
                 rows between 0 preceding and 12 following) 
from vin_temp_table

但收到此错误消息:

array_agg_transfn called in non-aggregate context

是否可以在接下来的n行中从列值构建数组?

2 个答案:

答案 0 :(得分:1)

这适用于Postgres 9.3:

SELECT week_value
     , array_agg(week_value) OVER(ORDER BY prod_name, week_date DESC
                                  ROWS BETWEEN 0 PRECEDING AND 12 FOLLOWING)
FROM   tbl

-> SQLfiddle for 9.3

但不是版本8.4:

-> SQLfiddle for 8.4

语法ROWS BETWEEN frame_start AND frame_end是在Postgres 9.0中引入的,在8.4中不可用。将current manual与其8.4 counterpart进行比较。

Postgres 8.4 is rather old by now and reaching EOL this summer。考虑升级到当前版本。

答案 1 :(得分:0)

如果array_agg在您的版本中不起作用,请尝试使用此方法

WITH Q AS(
  SELECT week,
         row_number() over (order by week) rn
  FROM test
)
SELECT week,
       ( SELECT array_agg(q2.week) 
         FROM q q2
         WHERE q2.rn BETWEEN q1.rn
                     AND q1.rn + 12
       )
FROM q q1;

工作演示(在8.4.17上) - > http://sqlfiddle.com/#!11/7eda9/1
但它可能很慢。