Get column values from multiple rows as array

冷暖自知 提交于 2019-12-25 07:48:26

问题


I am trying to fetch column values as an array in order to use them in the function array_agg_transfn() to calculate the median value as defined in the Postgres Wiki.

The column values of a particular column I fetch based on the current row. For example, 13 rows below the current row. I tried using the following query:

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

But got this error message:

array_agg_transfn called in non-aggregate context

Is it possible to build an array from column-values in the next n rows?


回答1:


This works just fine with 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

But not in version 8.4:

-> SQLfiddle for 8.4

The syntax ROWS BETWEEN frame_start AND frame_end was introduced with Postgres 9.0 and is not available in 8.4. Compare the current manual with its 8.4 counterpart.

Postgres 8.4 is rather old by now and reaching EOL this summer. Consider upgrading to the current version.




回答2:


If array_agg doesn't work in your version, then try this approach

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;

working demo (on 8.4.17) --> http://sqlfiddle.com/#!11/7eda9/1
but it can be slow.



来源:https://stackoverflow.com/questions/21993021/get-column-values-from-multiple-rows-as-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!