按行计算聚合值

时间:2012-10-25 22:02:23

标签: arrays aggregate window-functions postgresql-9.2

我有一系列行,我需要将这些行的值聚合到N元素组中,从当前行和N-1后续行累积值。

N=3,数据为:

VALUES (1),(2),(3),(4),(5);

我想收到以下一组行(数组):

{1,2,3}
{2,3,4}
{3,4,5}
{4,5}
{5}

重要的是,N是一个变量,所以我不能使用连接。

1 个答案:

答案 0 :(得分:1)

嗯,这可以解决using frames together with window functions

主题中的问题可以这样解决:

WITH v(v) AS (VALUES (1),(2),(3),(4),(5))
SELECT v,
       array_agg(v) OVER (ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING) AS arr
  FROM v;

以下示例说明了如何获取完整数组的列表,即消除那些不包含所有N条目的数组:

WITH cnt(c) AS (SELECT 3),
     val(v) AS (VALUES (1),(2),(3),(4),(5)),
     arr AS
(SELECT v,
        array_agg(v) OVER (ROWS BETWEEN CURRENT ROW
                           AND (SELECT c-1 FROM cnt) FOLLOWING) AS arr
   FROM val)
SELECT v,arr
  FROM arr
 WHERE array_upper(arr,1) = (SELECT c FROM cnt);

我真的很喜欢窗口功能!