前一行和非当前行

preceding and NOT current row

我正在尝试使用以下方法获取 postgres 中结果集的去年平均值:

SELECT
    *,
   avg(units) OVER (                                              -- 3
       ORDER BY to_date(isoyear::text || '-' || week::text, 'IYYY-IW')      -- 1
       RANGE between interval '1 year' preceding and 1 preceding )
FROM
    mytable
   order by isoyear,week;

但是我收到了这个错误:

SQL Error [22000]: ERROR: can't coerce leading frame bound to type of trailing frame bound Hint: specify the leading and trailing frame bounds as the same type

我刚刚尝试过,但出现语法错误:

RANGE between interval '1 year' preceding)

我错过了什么?我不需要前一行和当前行,我只需要 1 年前的前行..

谢谢

您需要范围的两个边界具有一致的数据类型 - 在这里,这将是间隔。一种表达你想要的方式是:

RANGE between interval '1 year' preceding and interval '1 second' preceding

基本上这会过滤掉直到前一秒的行:所以这会排除当前行,而不排除其他行,因为您的表达式无论如何都不包含秒数。