聚合 window 中的过滤子句未按预期丢弃行

Filter clause in aggregate window not discarding rows as expected

我希望过滤器子句在将行传递给 window 函数之前丢弃行。来自 docs:

If FILTER is specified, then only the input rows for which the filter_clause evaluates to true are fed to the window function; other rows are discarded. Only window functions that are aggregates accept a FILTER clause.

然而,下面的测试似乎与此矛盾:

create table test_1 as
select generate_series(1,10) as num;    

select
  *,
  sum(num) over last_2,
  sum(num) filter (where  num % 2 = 0) over last_2
from test_1
window
    last_2 as (order by num rows 1 preceding)
;

这个returns:

 num | sum |  sum   
-----+-----+--------
   1 |   1 | [null]
   2 |   3 |      2
   3 |   5 |      2
   4 |   7 |      4
   5 |   9 |      4
   6 |  11 |      6
   7 |  13 |      6
   8 |  15 |      8
   9 |  17 |      8
  10 |  19 |     10
(10 rows)

以第四行为例。这里聚合函数应该接收最后两个偶数行(即 2 和 4)。所以我希望这个总和是 6.

我误会了什么?

注意:这是一个人为的例子,它提炼了我实际上正在努力解决的问题。显然有更好的方法来求偶数的移动和。

over 子句优先于 filter 子句。所以你拿 last_2 (即当前行和它的前一行)并从中过滤,这只得到一行(偶数)。

你要找的是这个:

sum(case when num % 2 = 0 then num else 0 end) over last_2