我试图从过去两年内选择最大值。
例如,如果我有一个表,如下所示:

|person_id | pass_or_fail | timestamp|
|----------|--------------|-----------|
|1234      | 1            | 1990-01-01|
|1234      | 0            | 1995-01-01|
|1234      | NULL         | 1995-12-12|
|6789      | 0            | 1990-01-01|
|6789      | 0            | 1991-01-01|
|6789      | 1            | 1995-01-01|
|6789      | 1            | 1996-01-01|
|6789      | 0            | 1997-01-01|
|6789      | NULL         | 1997-03-03|

我想从我的查询中得到以下信息:
person_id |highest_grade_from_past_two_years | pass_or_fail | timestamp
1234      |1                                 | 1            | 1990-01-01
1234      |0                                 | 0            | 1995-01-01
1234      |0                                 | NULL         | 1995-12-12
6789      |0                                 | 0            | 1990-01-01
6789      |0                                 | 0            | 1991-01-01
6789      |1                                 | 1            | 1995-01-01
6789      |1                                 | 1            | 1996-01-01
6789      |1                                 | 0            | 1997-01-01
6789      |1                                 | NULL         | 1997-03-03

我如何编写窗口函数来给出这个结果?

最佳答案

我看不出使用窗口函数的明显方法。相关的子查询或横向联接将起作用:

select t.*,
       (select max(t2.pass_or_fail)
        from t t2
        where t2.person_id = t.person_id and
              t2.timestamp <= t.timestamp and
              t2.timestamp >= t.timestamp - interval '2 year'
       ) as highest_grade_from_past_two_years
from t;

我认为窗口函数最接近的是范围规范。但是,Postgres不支持带有precedingrange规范。

10-05 23:07